Fixes libstdc++/2079
[official-gcc.git] / gcc / cppfiles.c
blob25bc37df1a8f426d3b78515ada305e326e62a63e
1 /* Part of CPP library. (include file handling)
2 Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1998,
3 1999, 2000, 2001 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 "cpplib.h"
26 #include "cpphash.h"
27 #include "intl.h"
28 #include "mkdeps.h"
29 #include "splay-tree.h"
31 #ifdef HAVE_MMAP_FILE
32 # include <sys/mman.h>
33 # ifndef MMAP_THRESHOLD
34 # define MMAP_THRESHOLD 3 /* Minimum page count to mmap the file. */
35 # endif
37 #else /* No MMAP_FILE */
38 # undef MMAP_THRESHOLD
39 # define MMAP_THRESHOLD 0
40 #endif
42 #ifndef O_BINARY
43 # define O_BINARY 0
44 #endif
46 #ifndef INCLUDE_LEN_FUDGE
47 # define INCLUDE_LEN_FUDGE 0
48 #endif
50 /* If errno is inspected immediately after a system call fails, it will be
51 nonzero, and no error number will ever be zero. */
52 #ifndef ENOENT
53 # define ENOENT 0
54 #endif
55 #ifndef ENOTDIR
56 # define ENOTDIR 0
57 #endif
58 #ifndef ENOMEM
59 # define ENOMEM 0
60 #endif
62 /* Suppress warning about function macros used w/o arguments in traditional
63 C. It is unlikely that glibc's strcmp macro helps this file at all. */
64 #undef strcmp
66 /* This structure is used for the table of all includes. */
67 struct include_file
69 const char *name; /* actual path name of file */
70 const cpp_hashnode *cmacro; /* macro, if any, preventing reinclusion. */
71 const struct file_name_list *foundhere;
72 /* location in search path where file was
73 found, for #include_next and sysp. */
74 const unsigned char *buffer; /* pointer to cached file contents */
75 struct stat st; /* copy of stat(2) data for file */
76 int fd; /* fd open on file (short term storage only) */
77 unsigned short include_count; /* number of times file has been read */
78 unsigned short refcnt; /* number of stacked buffers using this file */
79 unsigned char mapped; /* file buffer is mmapped */
80 unsigned char defined; /* cmacro prevents inclusion in this state */
83 /* The cmacro works like this: If it's NULL, the file is to be
84 included again. If it's NEVER_REREAD, the file is never to be
85 included again. Otherwise it is a macro hashnode, and the file is
86 to be included again if the macro is defined or not as specified by
87 DEFINED. */
88 #define NEVER_REREAD ((const cpp_hashnode *)-1)
89 #define DO_NOT_REREAD(inc) \
90 ((inc)->cmacro && ((inc)->cmacro == NEVER_REREAD \
91 || ((inc)->cmacro->type == NT_MACRO) == (inc)->defined))
93 static struct file_name_map *read_name_map
94 PARAMS ((cpp_reader *, const char *));
95 static char *read_filename_string PARAMS ((int, FILE *));
96 static char *remap_filename PARAMS ((cpp_reader *, char *,
97 struct file_name_list *));
98 static struct file_name_list *actual_directory
99 PARAMS ((cpp_reader *, const char *));
100 static struct include_file *find_include_file
101 PARAMS ((cpp_reader *, const char *,
102 struct file_name_list *));
103 static struct include_file *open_file PARAMS ((cpp_reader *, const char *));
104 static void read_include_file PARAMS ((cpp_reader *, struct include_file *));
105 static void stack_include_file PARAMS ((cpp_reader *, struct include_file *));
106 static void purge_cache PARAMS ((struct include_file *));
107 static void destroy_include_file_node PARAMS ((splay_tree_value));
108 static int report_missing_guard PARAMS ((splay_tree_node, void *));
110 /* We use a splay tree to store information about all the include
111 files seen in this compilation. The key of each tree node is the
112 physical path to the file. The value is 0 if the file does not
113 exist, or a struct include_file pointer. */
115 static void
116 destroy_include_file_node (v)
117 splay_tree_value v;
119 struct include_file *f = (struct include_file *)v;
121 if (f)
123 purge_cache (f);
124 free (f); /* The tree is registered with free to free f->name. */
128 void
129 _cpp_init_includes (pfile)
130 cpp_reader *pfile;
132 pfile->all_include_files
133 = splay_tree_new ((splay_tree_compare_fn) strcmp,
134 (splay_tree_delete_key_fn) free,
135 destroy_include_file_node);
138 void
139 _cpp_cleanup_includes (pfile)
140 cpp_reader *pfile;
142 splay_tree_delete (pfile->all_include_files);
145 /* Mark a file to not be reread (e.g. #import, read failure). */
146 void
147 _cpp_never_reread (file)
148 struct include_file *file;
150 file->cmacro = NEVER_REREAD;
153 /* Put a file name in the splay tree, for the sake of cpp_included ().
154 Assume that FNAME has already had its path simplified. */
155 void
156 _cpp_fake_include (pfile, fname)
157 cpp_reader *pfile;
158 const char *fname;
160 splay_tree_node nd;
162 nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) fname);
163 if (! nd)
165 struct include_file *file = xcnew (struct include_file);
166 file->name = xstrdup (fname);
167 splay_tree_insert (pfile->all_include_files,
168 (splay_tree_key) file->name,
169 (splay_tree_value) file);
173 /* Given a file name, look it up in the cache; if there is no entry,
174 create one with a non-NULL value (regardless of success in opening
175 the file). If the file doesn't exist or is inaccessible, this
176 entry is flagged so we don't attempt to open it again in the
177 future. If the file isn't open, open it. The empty string is
178 interpreted as stdin.
180 Returns an include_file structure with an open file descriptor on
181 success, or NULL on failure. */
183 static struct include_file *
184 open_file (pfile, filename)
185 cpp_reader *pfile;
186 const char *filename;
188 splay_tree_node nd;
189 struct include_file *file;
191 nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) filename);
193 if (nd)
195 file = (struct include_file *) nd->value;
197 /* Don't retry opening if we failed previously. */
198 if (file->fd == -2)
199 return 0;
201 /* Don't reopen an idempotent file. */
202 if (DO_NOT_REREAD (file))
203 return file;
205 /* Don't reopen one which is already loaded. */
206 if (file->buffer != NULL)
207 return file;
209 else
211 /* In particular, this clears foundhere. */
212 file = xcnew (struct include_file);
213 file->name = xstrdup (filename);
214 splay_tree_insert (pfile->all_include_files,
215 (splay_tree_key) file->name,
216 (splay_tree_value) file);
219 /* We used to open files in nonblocking mode, but that caused more
220 problems than it solved. Do take care not to acquire a
221 controlling terminal by mistake (this can't happen on sane
222 systems, but paranoia is a virtue).
224 Use the three-argument form of open even though we aren't
225 specifying O_CREAT, to defend against broken system headers.
227 O_BINARY tells some runtime libraries (notably DJGPP) not to do
228 newline translation; we can handle DOS line breaks just fine
229 ourselves.
231 Special case: the empty string is translated to stdin. */
233 if (filename[0] == '\0')
234 file->fd = 0;
235 else
236 file->fd = open (filename, O_RDONLY | O_NOCTTY | O_BINARY, 0666);
238 if (file->fd != -1 && fstat (file->fd, &file->st) == 0)
240 /* Mark a regular, zero-length file never-reread now. */
241 if (S_ISREG (file->st.st_mode) && file->st.st_size == 0)
243 _cpp_never_reread (file);
244 close (file->fd);
245 file->fd = -1;
248 return file;
251 /* Don't issue an error message if the file doesn't exist. */
252 if (errno != ENOENT && errno != ENOTDIR)
253 cpp_error_from_errno (pfile, filename);
255 /* Create a negative node for this path, and return null. */
256 file->fd = -2;
258 return 0;
261 /* Place the file referenced by INC into a new buffer on PFILE's
262 stack. If there are errors, or the file should not be re-included,
263 a null buffer is pushed. */
265 static void
266 stack_include_file (pfile, inc)
267 cpp_reader *pfile;
268 struct include_file *inc;
270 size_t len = 0;
271 cpp_buffer *fp;
272 int sysp, deps_sysp;
274 /* We'll try removing deps_sysp after the release of 3.0. */
275 deps_sysp = pfile->system_include_depth != 0;
276 sysp = ((pfile->buffer && pfile->buffer->sysp)
277 || (inc->foundhere && inc->foundhere->sysp));
279 /* For -M, add the file to the dependencies on its first inclusion. */
280 if (CPP_OPTION (pfile, print_deps) > deps_sysp && !inc->include_count)
281 deps_add_dep (pfile->deps, inc->name);
283 /* We don't want multiple include guard advice for the main file. */
284 if (pfile->buffer)
285 inc->include_count++;
287 /* Not in cache? */
288 if (! inc->buffer)
289 read_include_file (pfile, inc);
291 if (! DO_NOT_REREAD (inc))
292 len = inc->st.st_size;
294 /* Push a buffer. */
295 fp = cpp_push_buffer (pfile, inc->buffer, len, BUF_FILE, inc->name);
296 fp->inc = inc;
297 fp->inc->refcnt++;
298 fp->sysp = sysp;
300 /* The ->actual_dir field is only used when ignore_srcdir is not in effect;
301 see do_include */
302 if (!CPP_OPTION (pfile, ignore_srcdir))
303 fp->actual_dir = actual_directory (pfile, inc->name);
305 /* Initialise controlling macro state. */
306 pfile->mi_state = MI_OUTSIDE;
307 pfile->mi_cmacro = 0;
308 pfile->include_depth++;
310 /* Generate the call back. */
311 fp->lineno = 0;
312 _cpp_do_file_change (pfile, FC_ENTER, 0, 0);
313 fp->lineno = 1;
316 /* Read the file referenced by INC into the file cache.
318 If fd points to a plain file, we might be able to mmap it; we can
319 definitely allocate the buffer all at once. If fd is a pipe or
320 terminal, we can't do either. If fd is something weird, like a
321 block device or a directory, we don't want to read it at all.
323 Unfortunately, different systems use different st.st_mode values
324 for pipes: some have S_ISFIFO, some S_ISSOCK, some are buggy and
325 zero the entire struct stat except a couple fields. Hence we don't
326 even try to figure out what something is, except for plain files,
327 directories, and block devices.
329 FIXME: Flush file cache and try again if we run out of memory. */
331 static void
332 read_include_file (pfile, inc)
333 cpp_reader *pfile;
334 struct include_file *inc;
336 ssize_t size, offset, count;
337 U_CHAR *buf;
338 #if MMAP_THRESHOLD
339 static int pagesize = -1;
340 #endif
342 if (DO_NOT_REREAD (inc))
343 return;
345 if (S_ISREG (inc->st.st_mode))
347 /* off_t might have a wider range than ssize_t - in other words,
348 the max size of a file might be bigger than the address
349 space. We can't handle a file that large. (Anyone with
350 a single source file bigger than 2GB needs to rethink
351 their coding style.) Some systems (e.g. AIX 4.1) define
352 SSIZE_MAX to be much smaller than the actual range of the
353 type. Use INTTYPE_MAXIMUM unconditionally to ensure this
354 does not bite us. */
355 if (inc->st.st_size > INTTYPE_MAXIMUM (ssize_t))
357 cpp_error (pfile, "%s is too large", inc->name);
358 goto fail;
360 size = inc->st.st_size;
362 inc->mapped = 0;
363 #if MMAP_THRESHOLD
364 if (pagesize == -1)
365 pagesize = getpagesize ();
367 if (size / pagesize >= MMAP_THRESHOLD)
369 buf = (U_CHAR *) mmap (0, size, PROT_READ, MAP_PRIVATE, inc->fd, 0);
370 if (buf == (U_CHAR *)-1)
371 goto perror_fail;
372 inc->mapped = 1;
374 else
375 #endif
377 buf = (U_CHAR *) xmalloc (size);
378 offset = 0;
379 while (offset < size)
381 count = read (inc->fd, buf + offset, size - offset);
382 if (count < 0)
383 goto perror_fail;
384 if (count == 0)
386 cpp_warning (pfile, "%s is shorter than expected", inc->name);
387 break;
389 offset += count;
393 else if (S_ISBLK (inc->st.st_mode))
395 cpp_error (pfile, "%s is a block device", inc->name);
396 goto fail;
398 else if (S_ISDIR (inc->st.st_mode))
400 cpp_error (pfile, "%s is a directory", inc->name);
401 goto fail;
403 else
405 /* 8 kilobytes is a sensible starting size. It ought to be
406 bigger than the kernel pipe buffer, and it's definitely
407 bigger than the majority of C source files. */
408 size = 8 * 1024;
410 buf = (U_CHAR *) xmalloc (size);
411 offset = 0;
412 while ((count = read (inc->fd, buf + offset, size - offset)) > 0)
414 offset += count;
415 if (offset == size)
416 buf = xrealloc (buf, (size *= 2));
418 if (count < 0)
419 goto perror_fail;
421 if (offset < size)
422 buf = xrealloc (buf, offset);
423 inc->st.st_size = offset;
426 close (inc->fd);
427 inc->buffer = buf;
428 inc->fd = -1;
429 return;
431 perror_fail:
432 cpp_error_from_errno (pfile, inc->name);
433 fail:
434 /* Do not try to read this file again. */
435 close (inc->fd);
436 inc->fd = -1;
437 _cpp_never_reread (inc);
438 return;
441 static void
442 purge_cache (inc)
443 struct include_file *inc;
445 if (inc->buffer)
447 #if MMAP_THRESHOLD
448 if (inc->mapped)
449 munmap ((PTR) inc->buffer, inc->st.st_size);
450 else
451 #endif
452 free ((PTR) inc->buffer);
453 inc->buffer = NULL;
457 /* Return 1 if the file named by FNAME has been included before in
458 any context, 0 otherwise. */
460 cpp_included (pfile, fname)
461 cpp_reader *pfile;
462 const char *fname;
464 struct file_name_list *path;
465 char *name;
466 splay_tree_node nd;
468 if (IS_ABSOLUTE_PATHNAME (fname))
470 /* Just look it up. */
471 nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) fname);
472 return (nd && nd->value);
475 /* Search directory path for the file. */
476 name = (char *) alloca (strlen (fname) + pfile->max_include_len
477 + 2 + INCLUDE_LEN_FUDGE);
478 for (path = CPP_OPTION (pfile, quote_include); path; path = path->next)
480 memcpy (name, path->name, path->nlen);
481 name[path->nlen] = '/';
482 strcpy (&name[path->nlen+1], fname);
483 _cpp_simplify_pathname (name);
484 if (CPP_OPTION (pfile, remap))
485 name = remap_filename (pfile, name, path);
487 nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) name);
488 if (nd && nd->value)
489 return 1;
491 return 0;
494 /* Search for include file FNAME in the include chain starting at
495 SEARCH_START. Return 0 if there is no such file (or it's un-openable),
496 otherwise an include_file structure. */
498 static struct include_file *
499 find_include_file (pfile, fname, search_start)
500 cpp_reader *pfile;
501 const char *fname;
502 struct file_name_list *search_start;
504 struct file_name_list *path;
505 char *name;
506 struct include_file *file;
508 if (IS_ABSOLUTE_PATHNAME (fname))
509 return open_file (pfile, fname);
511 /* Search directory path for the file. */
512 name = (char *) alloca (strlen (fname) + pfile->max_include_len
513 + 2 + INCLUDE_LEN_FUDGE);
514 for (path = search_start; path; path = path->next)
516 memcpy (name, path->name, path->nlen);
517 name[path->nlen] = '/';
518 strcpy (&name[path->nlen+1], fname);
519 _cpp_simplify_pathname (name);
520 if (CPP_OPTION (pfile, remap))
521 name = remap_filename (pfile, name, path);
523 file = open_file (pfile, name);
524 if (file)
526 file->foundhere = path;
527 return file;
530 return 0;
533 /* Not everyone who wants to set system-header-ness on a buffer can
534 see the details of a buffer. This is an exported interface because
535 fix-header needs it. */
536 void
537 cpp_make_system_header (pfile, syshdr, externc)
538 cpp_reader *pfile;
539 int syshdr, externc;
541 int flags = 0;
543 /* 1 = system header, 2 = system header to be treated as C. */
544 if (syshdr)
545 flags = 1 + (externc != 0);
546 pfile->buffer->sysp = flags;
547 _cpp_do_file_change (pfile, FC_RENAME, pfile->buffer->nominal_fname,
548 pfile->buffer->lineno);
551 /* Report on all files that might benefit from a multiple include guard.
552 Triggered by -H. */
553 void
554 _cpp_report_missing_guards (pfile)
555 cpp_reader *pfile;
557 int banner = 0;
558 splay_tree_foreach (pfile->all_include_files, report_missing_guard,
559 (PTR) &banner);
562 static int
563 report_missing_guard (n, b)
564 splay_tree_node n;
565 void *b;
567 struct include_file *f = (struct include_file *) n->value;
568 int *bannerp = (int *)b;
570 if (f && f->cmacro == 0 && f->include_count == 1)
572 if (*bannerp == 0)
574 fputs (_("Multiple include guards may be useful for:\n"), stderr);
575 *bannerp = 1;
577 fputs (f->name, stderr);
578 putc ('\n', stderr);
580 return 0;
583 void
584 _cpp_execute_include (pfile, header, no_reinclude, include_next)
585 cpp_reader *pfile;
586 const cpp_token *header;
587 int no_reinclude;
588 int include_next;
590 struct file_name_list *search_start = 0;
591 unsigned int len = header->val.str.len;
592 unsigned int angle_brackets = header->type == CPP_HEADER_NAME;
593 struct include_file *inc;
594 char *fname;
595 int print_dep;
597 /* Help protect #include or similar from recursion. */
598 if (pfile->buffer_stack_depth >= CPP_STACK_MAX)
600 cpp_fatal (pfile, "#include nested too deeply");
601 return;
604 /* Check we've tidied up #include before entering the buffer. */
605 if (pfile->context->prev)
607 cpp_ice (pfile, "attempt to push file buffer with contexts stacked");
608 return;
611 /* For #include_next, skip in the search path past the dir in which
612 the current file was found. If this is the last directory in the
613 search path, don't include anything. If the current file was
614 specified with an absolute path, use the normal search logic. If
615 this is the primary source file, use the normal search logic and
616 generate a warning. */
617 if (include_next)
619 if (! pfile->buffer->prev)
620 cpp_warning (pfile, "#include_next in primary source file");
621 else
623 if (pfile->buffer->inc->foundhere)
625 search_start = pfile->buffer->inc->foundhere->next;
626 if (! search_start)
627 return;
632 fname = alloca (len + 1);
633 memcpy (fname, header->val.str.text, len);
634 fname[len] = '\0';
636 if (!search_start)
638 if (angle_brackets)
639 search_start = CPP_OPTION (pfile, bracket_include);
640 else if (CPP_OPTION (pfile, ignore_srcdir))
641 search_start = CPP_OPTION (pfile, quote_include);
642 else
643 search_start = CPP_BUFFER (pfile)->actual_dir;
645 if (!search_start)
647 cpp_error (pfile, "No include path in which to find %s", fname);
648 return;
652 inc = find_include_file (pfile, fname, search_start);
653 if (inc)
655 if (angle_brackets)
656 pfile->system_include_depth++;
658 stack_include_file (pfile, inc);
660 if (! DO_NOT_REREAD (inc))
662 if (no_reinclude)
663 _cpp_never_reread (inc);
665 /* Handle -H option. */
666 if (CPP_OPTION (pfile, print_include_names))
668 cpp_buffer *fp = CPP_BUFFER (pfile);
669 while ((fp = CPP_PREV_BUFFER (fp)) != NULL)
670 putc ('.', stderr);
671 fprintf (stderr, " %s\n", inc->name);
675 return;
678 /* We will try making the RHS pfile->buffer->sysp after 3.0. */
679 print_dep = CPP_PRINT_DEPS(pfile) > (angle_brackets
680 || pfile->system_include_depth);
681 if (CPP_OPTION (pfile, print_deps_missing_files) && print_dep)
683 if (!angle_brackets || IS_ABSOLUTE_PATHNAME (fname))
684 deps_add_dep (pfile->deps, fname);
685 else
687 char *p;
688 struct file_name_list *ptr;
689 int len;
691 /* If requested as a system header, assume it belongs in
692 the first system header directory. */
693 if (CPP_OPTION (pfile, bracket_include))
694 ptr = CPP_OPTION (pfile, bracket_include);
695 else
696 ptr = CPP_OPTION (pfile, quote_include);
698 len = strlen (ptr->name);
699 p = (char *) alloca (len + strlen (fname) + 2);
700 if (len)
702 memcpy (p, ptr->name, len);
703 p[len++] = '/';
705 strcpy (p + len, fname);
706 _cpp_simplify_pathname (p);
707 deps_add_dep (pfile->deps, p);
710 /* If -M was specified, and this header file won't be added to
711 the dependency list, then don't count this as an error,
712 because we can still produce correct output. Otherwise, we
713 can't produce correct output, because there may be
714 dependencies we need inside the missing file, and we don't
715 know what directory this missing file exists in. */
716 else if (CPP_PRINT_DEPS (pfile) && ! print_dep)
717 cpp_warning (pfile, "No include path in which to find %s", fname);
718 else
719 cpp_error_from_errno (pfile, fname);
722 /* Locate file F, and determine whether it is newer than PFILE. Return -1,
723 if F cannot be located or dated, 1, if it is newer and 0 if older. */
725 _cpp_compare_file_date (pfile, f)
726 cpp_reader *pfile;
727 const cpp_token *f;
729 unsigned int len = f->val.str.len;
730 char *fname;
731 struct file_name_list *search_start;
732 struct include_file *inc;
734 if (f->type == CPP_HEADER_NAME)
735 search_start = CPP_OPTION (pfile, bracket_include);
736 else if (CPP_OPTION (pfile, ignore_srcdir))
737 search_start = CPP_OPTION (pfile, quote_include);
738 else
739 search_start = CPP_BUFFER (pfile)->actual_dir;
741 fname = alloca (len + 1);
742 memcpy (fname, f->val.str.text, len);
743 fname[len] = '\0';
744 inc = find_include_file (pfile, fname, search_start);
746 if (!inc)
747 return -1;
748 if (inc->fd > 0)
750 close (inc->fd);
751 inc->fd = -1;
754 return inc->st.st_mtime > CPP_BUFFER (pfile)->inc->st.st_mtime;
758 /* Push an input buffer and load it up with the contents of FNAME.
759 If FNAME is "", read standard input. */
761 _cpp_read_file (pfile, fname)
762 cpp_reader *pfile;
763 const char *fname;
765 struct include_file *f = open_file (pfile, fname);
767 if (f == NULL)
769 cpp_error_from_errno (pfile, fname);
770 return 0;
773 stack_include_file (pfile, f);
774 return 1;
777 /* Do appropriate cleanup when a file buffer is popped off the input
778 stack. */
779 void
780 _cpp_pop_file_buffer (pfile, buf)
781 cpp_reader *pfile;
782 cpp_buffer *buf;
784 struct include_file *inc = buf->inc;
786 if (pfile->system_include_depth)
787 pfile->system_include_depth--;
788 if (pfile->include_depth)
789 pfile->include_depth--;
791 /* Record the inclusion-preventing macro and its definedness. */
792 if (pfile->mi_state == MI_OUTSIDE && inc->cmacro != NEVER_REREAD)
794 /* This could be NULL meaning no controlling macro. */
795 inc->cmacro = pfile->mi_cmacro;
796 inc->defined = 1;
799 /* Invalidate control macros in the #including file. */
800 pfile->mi_state = MI_FAILED;
802 inc->refcnt--;
803 if (inc->refcnt == 0 && DO_NOT_REREAD (inc))
804 purge_cache (inc);
807 /* The file_name_map structure holds a mapping of file names for a
808 particular directory. This mapping is read from the file named
809 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
810 map filenames on a file system with severe filename restrictions,
811 such as DOS. The format of the file name map file is just a series
812 of lines with two tokens on each line. The first token is the name
813 to map, and the second token is the actual name to use. */
815 struct file_name_map
817 struct file_name_map *map_next;
818 char *map_from;
819 char *map_to;
822 #define FILE_NAME_MAP_FILE "header.gcc"
824 /* Read a space delimited string of unlimited length from a stdio
825 file. */
827 static char *
828 read_filename_string (ch, f)
829 int ch;
830 FILE *f;
832 char *alloc, *set;
833 int len;
835 len = 20;
836 set = alloc = xmalloc (len + 1);
837 if (! is_space(ch))
839 *set++ = ch;
840 while ((ch = getc (f)) != EOF && ! is_space(ch))
842 if (set - alloc == len)
844 len *= 2;
845 alloc = xrealloc (alloc, len + 1);
846 set = alloc + len / 2;
848 *set++ = ch;
851 *set = '\0';
852 ungetc (ch, f);
853 return alloc;
856 /* This structure holds a linked list of file name maps, one per directory. */
858 struct file_name_map_list
860 struct file_name_map_list *map_list_next;
861 char *map_list_name;
862 struct file_name_map *map_list_map;
865 /* Read the file name map file for DIRNAME. */
867 static struct file_name_map *
868 read_name_map (pfile, dirname)
869 cpp_reader *pfile;
870 const char *dirname;
872 register struct file_name_map_list *map_list_ptr;
873 char *name;
874 FILE *f;
876 /* Check the cache of directories, and mappings in their remap file. */
877 for (map_list_ptr = CPP_OPTION (pfile, map_list); map_list_ptr;
878 map_list_ptr = map_list_ptr->map_list_next)
879 if (! strcmp (map_list_ptr->map_list_name, dirname))
880 return map_list_ptr->map_list_map;
882 map_list_ptr = ((struct file_name_map_list *)
883 xmalloc (sizeof (struct file_name_map_list)));
884 map_list_ptr->map_list_name = xstrdup (dirname);
886 /* The end of the list ends in NULL. */
887 map_list_ptr->map_list_map = NULL;
889 name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
890 strcpy (name, dirname);
891 if (*dirname)
892 strcat (name, "/");
893 strcat (name, FILE_NAME_MAP_FILE);
894 f = fopen (name, "r");
896 /* Silently return NULL if we cannot open. */
897 if (f)
899 int ch;
900 int dirlen = strlen (dirname);
902 while ((ch = getc (f)) != EOF)
904 char *from, *to;
905 struct file_name_map *ptr;
907 if (is_space(ch))
908 continue;
909 from = read_filename_string (ch, f);
910 while ((ch = getc (f)) != EOF && is_hspace(ch))
912 to = read_filename_string (ch, f);
914 ptr = ((struct file_name_map *)
915 xmalloc (sizeof (struct file_name_map)));
916 ptr->map_from = from;
918 /* Make the real filename absolute. */
919 if (IS_ABSOLUTE_PATHNAME (to))
920 ptr->map_to = to;
921 else
923 ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
924 strcpy (ptr->map_to, dirname);
925 ptr->map_to[dirlen] = '/';
926 strcpy (ptr->map_to + dirlen + 1, to);
927 free (to);
930 ptr->map_next = map_list_ptr->map_list_map;
931 map_list_ptr->map_list_map = ptr;
933 while ((ch = getc (f)) != '\n')
934 if (ch == EOF)
935 break;
937 fclose (f);
940 /* Add this information to the cache. */
941 map_list_ptr->map_list_next = CPP_OPTION (pfile, map_list);
942 CPP_OPTION (pfile, map_list) = map_list_ptr;
944 return map_list_ptr->map_list_map;
947 /* Remap NAME based on the file_name_map (if any) for LOC. */
949 static char *
950 remap_filename (pfile, name, loc)
951 cpp_reader *pfile;
952 char *name;
953 struct file_name_list *loc;
955 struct file_name_map *map;
956 const char *from, *p;
957 char *dir;
959 if (! loc->name_map)
961 loc->name_map = read_name_map (pfile, loc->name ? loc->name : ".");
962 if (! loc->name_map)
963 return name;
966 from = name + strlen (loc->name) + 1;
968 for (map = loc->name_map; map; map = map->map_next)
969 if (!strcmp (map->map_from, from))
970 return map->map_to;
972 /* Try to find a mapping file for the particular directory we are
973 looking in. Thus #include <sys/types.h> will look up sys/types.h
974 in /usr/include/header.gcc and look up types.h in
975 /usr/include/sys/header.gcc. */
976 p = strrchr (name, '/');
977 if (!p)
978 return name;
980 /* We know p != name as absolute paths don't call remap_filename. */
981 if (p == name)
982 cpp_ice (pfile, "absolute file name in remap_filename");
984 dir = (char *) alloca (p - name + 1);
985 memcpy (dir, name, p - name);
986 dir[p - name] = '\0';
987 from = p + 1;
989 for (map = read_name_map (pfile, dir); map; map = map->map_next)
990 if (! strcmp (map->map_from, from))
991 return map->map_to;
993 return name;
996 /* Given a path FNAME, extract the directory component and place it
997 onto the actual_dirs list. Return a pointer to the allocated
998 file_name_list structure. These structures are used to implement
999 current-directory "" include searching. */
1001 static struct file_name_list *
1002 actual_directory (pfile, fname)
1003 cpp_reader *pfile;
1004 const char *fname;
1006 char *last_slash, *dir;
1007 size_t dlen;
1008 struct file_name_list *x;
1010 dir = xstrdup (fname);
1011 last_slash = strrchr (dir, '/');
1012 if (last_slash)
1014 if (last_slash == dir)
1016 dlen = 1;
1017 last_slash[1] = '\0';
1019 else
1021 dlen = last_slash - dir;
1022 *last_slash = '\0';
1025 else
1027 free (dir);
1028 dir = xstrdup (".");
1029 dlen = 1;
1032 if (dlen > pfile->max_include_len)
1033 pfile->max_include_len = dlen;
1035 for (x = pfile->actual_dirs; x; x = x->alloc)
1036 if (!strcmp (x->name, dir))
1038 free (dir);
1039 return x;
1042 /* Not found, make a new one. */
1043 x = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1044 x->name = dir;
1045 x->nlen = dlen;
1046 x->next = CPP_OPTION (pfile, quote_include);
1047 x->alloc = pfile->actual_dirs;
1048 x->sysp = pfile->buffer->sysp;
1049 x->name_map = NULL;
1051 pfile->actual_dirs = x;
1052 return x;
1055 /* Simplify a path name in place, deleting redundant components. This
1056 reduces OS overhead and guarantees that equivalent paths compare
1057 the same (modulo symlinks).
1059 Transforms made:
1060 foo/bar/../quux foo/quux
1061 foo/./bar foo/bar
1062 foo//bar foo/bar
1063 /../quux /quux
1064 //quux //quux (POSIX allows leading // as a namespace escape)
1066 Guarantees no trailing slashes. All transforms reduce the length
1067 of the string.
1069 void
1070 _cpp_simplify_pathname (path)
1071 char *path;
1073 char *from, *to;
1074 char *base;
1075 int absolute = 0;
1077 #if defined (HAVE_DOS_BASED_FILE_SYSTEM)
1078 /* Convert all backslashes to slashes. */
1079 for (from = path; *from; from++)
1080 if (*from == '\\') *from = '/';
1082 /* Skip over leading drive letter if present. */
1083 if (ISALPHA (path[0]) && path[1] == ':')
1084 from = to = &path[2];
1085 else
1086 from = to = path;
1087 #else
1088 from = to = path;
1089 #endif
1091 /* Remove redundant initial /s. */
1092 if (*from == '/')
1094 absolute = 1;
1095 to++;
1096 from++;
1097 if (*from == '/')
1099 if (*++from == '/')
1100 /* 3 or more initial /s are equivalent to 1 /. */
1101 while (*++from == '/');
1102 else
1103 /* On some hosts // differs from /; Posix allows this. */
1104 to++;
1107 base = to;
1109 for (;;)
1111 while (*from == '/')
1112 from++;
1114 if (from[0] == '.' && from[1] == '/')
1115 from += 2;
1116 else if (from[0] == '.' && from[1] == '\0')
1117 goto done;
1118 else if (from[0] == '.' && from[1] == '.' && from[2] == '/')
1120 if (base == to)
1122 if (absolute)
1123 from += 3;
1124 else
1126 *to++ = *from++;
1127 *to++ = *from++;
1128 *to++ = *from++;
1129 base = to;
1132 else
1134 to -= 2;
1135 while (to > base && *to != '/') to--;
1136 if (*to == '/')
1137 to++;
1138 from += 3;
1141 else if (from[0] == '.' && from[1] == '.' && from[2] == '\0')
1143 if (base == to)
1145 if (!absolute)
1147 *to++ = *from++;
1148 *to++ = *from++;
1151 else
1153 to -= 2;
1154 while (to > base && *to != '/') to--;
1155 if (*to == '/')
1156 to++;
1158 goto done;
1160 else
1161 /* Copy this component and trailing /, if any. */
1162 while ((*to++ = *from++) != '/')
1164 if (!to[-1])
1166 to--;
1167 goto done;
1173 done:
1174 /* Trim trailing slash */
1175 if (to[0] == '/' && (!absolute || to > path+1))
1176 to--;
1178 /* Change the empty string to "." so that stat() on the result
1179 will always work. */
1180 if (to == path)
1181 *to++ = '.';
1183 *to = '\0';
1185 return;