49b7958e287645ecbaafcc10a30569f357621235
[gcc.git] / gcc / cppfiles.c
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
8
9 This program is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
22
23 #include "config.h"
24 #include "system.h"
25 #include "cpplib.h"
26 #include "cpphash.h"
27 #include "intl.h"
28 #include "mkdeps.h"
29 #include "splay-tree.h"
30
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
36
37 #else /* No MMAP_FILE */
38 # undef MMAP_THRESHOLD
39 # define MMAP_THRESHOLD 0
40 #endif
41
42 #ifndef O_BINARY
43 # define O_BINARY 0
44 #endif
45
46 #ifndef INCLUDE_LEN_FUDGE
47 # define INCLUDE_LEN_FUDGE 0
48 #endif
49
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
61
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
65
66 /* This structure is used for the table of all includes. */
67 struct include_file
68 {
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 */
81 };
82
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))
92
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 *));
109
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. */
114
115 static void
116 destroy_include_file_node (v)
117 splay_tree_value v;
118 {
119 struct include_file *f = (struct include_file *)v;
120
121 if (f)
122 {
123 purge_cache (f);
124 free (f); /* The tree is registered with free to free f->name. */
125 }
126 }
127
128 void
129 _cpp_init_includes (pfile)
130 cpp_reader *pfile;
131 {
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);
136 }
137
138 void
139 _cpp_cleanup_includes (pfile)
140 cpp_reader *pfile;
141 {
142 splay_tree_delete (pfile->all_include_files);
143 }
144
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;
149 {
150 file->cmacro = NEVER_REREAD;
151 }
152
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;
159 {
160 splay_tree_node nd;
161
162 nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) fname);
163 if (! nd)
164 {
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);
170 }
171 }
172
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.
178
179 Returns an include_file structure with an open file descriptor on
180 success, or NULL on failure. */
181
182 static struct include_file *
183 open_file (pfile, filename)
184 cpp_reader *pfile;
185 const char *filename;
186 {
187 splay_tree_node nd;
188 struct include_file *file;
189
190 nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) filename);
191
192 if (nd)
193 {
194 file = (struct include_file *) nd->value;
195
196 /* Don't retry opening if we failed previously. */
197 if (file->fd == -2)
198 return 0;
199
200 /* Don't reopen an idempotent file. */
201 if (DO_NOT_REREAD (file))
202 return file;
203
204 /* Don't reopen one which is already loaded. */
205 if (file->buffer != NULL)
206 return file;
207 }
208 else
209 {
210 /* In particular, this clears foundhere. */
211 file = xcnew (struct include_file);
212 file->name = xstrdup (filename);
213 splay_tree_insert (pfile->all_include_files,
214 (splay_tree_key) file->name,
215 (splay_tree_value) file);
216 }
217
218 /* We used to open files in nonblocking mode, but that caused more
219 problems than it solved. Do take care not to acquire a
220 controlling terminal by mistake (this can't happen on sane
221 systems, but paranoia is a virtue).
222
223 Use the three-argument form of open even though we aren't
224 specifying O_CREAT, to defend against broken system headers.
225
226 O_BINARY tells some runtime libraries (notably DJGPP) not to do
227 newline translation; we can handle DOS line breaks just fine
228 ourselves.
229
230 Special case: the empty string is translated to stdin. */
231
232 if (filename[0] == '\0')
233 file->fd = 0;
234 else
235 file->fd = open (filename, O_RDONLY | O_NOCTTY | O_BINARY, 0666);
236
237 if (file->fd != -1 && fstat (file->fd, &file->st) == 0)
238 {
239 /* Mark a regular, zero-length file never-reread now. */
240 if (S_ISREG (file->st.st_mode) && file->st.st_size == 0)
241 {
242 _cpp_never_reread (file);
243 close (file->fd);
244 file->fd = -1;
245 }
246
247 return file;
248 }
249
250 /* Don't issue an error message if the file doesn't exist. */
251 if (errno != ENOENT && errno != ENOTDIR)
252 cpp_error_from_errno (pfile, filename);
253
254 /* Create a negative node for this path, and return null. */
255 file->fd = -2;
256
257 return 0;
258 }
259
260 /* Place the file referenced by INC into a new buffer on PFILE's
261 stack. If there are errors, or the file should not be re-included,
262 a null buffer is pushed. */
263
264 static void
265 stack_include_file (pfile, inc)
266 cpp_reader *pfile;
267 struct include_file *inc;
268 {
269 size_t len = 0;
270 cpp_buffer *fp;
271 int sysp, deps_sysp;
272
273 /* We'll try removing deps_sysp after the release of 3.0. */
274 deps_sysp = pfile->system_include_depth != 0;
275 sysp = ((pfile->buffer && pfile->buffer->sysp)
276 || (inc->foundhere && inc->foundhere->sysp));
277
278 /* For -M, add the file to the dependencies on its first inclusion. */
279 if (CPP_OPTION (pfile, print_deps) > deps_sysp && !inc->include_count)
280 deps_add_dep (pfile->deps, inc->name);
281
282 /* We don't want multiple include guard advice for the main file. */
283 if (pfile->buffer)
284 inc->include_count++;
285
286 /* Not in cache? */
287 if (! inc->buffer)
288 read_include_file (pfile, inc);
289
290 if (! DO_NOT_REREAD (inc))
291 len = inc->st.st_size;
292
293 /* Push a buffer. */
294 fp = cpp_push_buffer (pfile, inc->buffer, len, BUF_FILE, inc->name);
295 fp->inc = inc;
296 fp->inc->refcnt++;
297 fp->sysp = sysp;
298
299 /* The ->actual_dir field is only used when ignore_srcdir is not in effect;
300 see do_include */
301 if (!CPP_OPTION (pfile, ignore_srcdir))
302 fp->actual_dir = actual_directory (pfile, inc->name);
303
304 /* Initialise controlling macro state. */
305 pfile->mi_state = MI_OUTSIDE;
306 pfile->mi_cmacro = 0;
307 pfile->include_depth++;
308
309 /* Generate the call back. */
310 fp->lineno = 0;
311 _cpp_do_file_change (pfile, FC_ENTER, 0, 0);
312 fp->lineno = 1;
313 }
314
315 /* Read the file referenced by INC into the file cache.
316
317 If fd points to a plain file, we might be able to mmap it; we can
318 definitely allocate the buffer all at once. If fd is a pipe or
319 terminal, we can't do either. If fd is something weird, like a
320 block device or a directory, we don't want to read it at all.
321
322 Unfortunately, different systems use different st.st_mode values
323 for pipes: some have S_ISFIFO, some S_ISSOCK, some are buggy and
324 zero the entire struct stat except a couple fields. Hence we don't
325 even try to figure out what something is, except for plain files,
326 directories, and block devices.
327
328 FIXME: Flush file cache and try again if we run out of memory. */
329
330 static void
331 read_include_file (pfile, inc)
332 cpp_reader *pfile;
333 struct include_file *inc;
334 {
335 ssize_t size, offset, count;
336 U_CHAR *buf;
337 #if MMAP_THRESHOLD
338 static int pagesize = -1;
339 #endif
340
341 if (DO_NOT_REREAD (inc))
342 return;
343
344 if (S_ISREG (inc->st.st_mode))
345 {
346 /* off_t might have a wider range than ssize_t - in other words,
347 the max size of a file might be bigger than the address
348 space. We can't handle a file that large. (Anyone with
349 a single source file bigger than 2GB needs to rethink
350 their coding style.) Some systems (e.g. AIX 4.1) define
351 SSIZE_MAX to be much smaller than the actual range of the
352 type. Use INTTYPE_MAXIMUM unconditionally to ensure this
353 does not bite us. */
354 if (inc->st.st_size > INTTYPE_MAXIMUM (ssize_t))
355 {
356 cpp_error (pfile, "%s is too large", inc->name);
357 goto fail;
358 }
359 size = inc->st.st_size;
360
361 inc->mapped = 0;
362 #if MMAP_THRESHOLD
363 if (pagesize == -1)
364 pagesize = getpagesize ();
365
366 if (size / pagesize >= MMAP_THRESHOLD)
367 {
368 buf = (U_CHAR *) mmap (0, size, PROT_READ, MAP_PRIVATE, inc->fd, 0);
369 if (buf == (U_CHAR *)-1)
370 goto perror_fail;
371 inc->mapped = 1;
372 }
373 else
374 #endif
375 {
376 buf = (U_CHAR *) xmalloc (size);
377 offset = 0;
378 while (offset < size)
379 {
380 count = read (inc->fd, buf + offset, size - offset);
381 if (count < 0)
382 goto perror_fail;
383 if (count == 0)
384 {
385 cpp_warning (pfile, "%s is shorter than expected", inc->name);
386 break;
387 }
388 offset += count;
389 }
390 }
391 }
392 else if (S_ISBLK (inc->st.st_mode))
393 {
394 cpp_error (pfile, "%s is a block device", inc->name);
395 goto fail;
396 }
397 else if (S_ISDIR (inc->st.st_mode))
398 {
399 cpp_error (pfile, "%s is a directory", inc->name);
400 goto fail;
401 }
402 else
403 {
404 /* 8 kilobytes is a sensible starting size. It ought to be
405 bigger than the kernel pipe buffer, and it's definitely
406 bigger than the majority of C source files. */
407 size = 8 * 1024;
408
409 buf = (U_CHAR *) xmalloc (size);
410 offset = 0;
411 while ((count = read (inc->fd, buf + offset, size - offset)) > 0)
412 {
413 offset += count;
414 if (offset == size)
415 buf = xrealloc (buf, (size *= 2));
416 }
417 if (count < 0)
418 goto perror_fail;
419
420 if (offset < size)
421 buf = xrealloc (buf, offset);
422 inc->st.st_size = offset;
423 }
424
425 close (inc->fd);
426 inc->buffer = buf;
427 inc->fd = -1;
428 return;
429
430 perror_fail:
431 cpp_error_from_errno (pfile, inc->name);
432 fail:
433 /* Do not try to read this file again. */
434 close (inc->fd);
435 inc->fd = -1;
436 _cpp_never_reread (inc);
437 return;
438 }
439
440 static void
441 purge_cache (inc)
442 struct include_file *inc;
443 {
444 if (inc->buffer)
445 {
446 #if MMAP_THRESHOLD
447 if (inc->mapped)
448 munmap ((PTR) inc->buffer, inc->st.st_size);
449 else
450 #endif
451 free ((PTR) inc->buffer);
452 inc->buffer = NULL;
453 }
454 }
455
456 /* Return 1 if the file named by FNAME has been included before in
457 any context, 0 otherwise. */
458 int
459 cpp_included (pfile, fname)
460 cpp_reader *pfile;
461 const char *fname;
462 {
463 struct file_name_list *path;
464 char *name;
465 splay_tree_node nd;
466
467 if (IS_ABSOLUTE_PATHNAME (fname))
468 {
469 /* Just look it up. */
470 nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) fname);
471 return (nd && nd->value);
472 }
473
474 /* Search directory path for the file. */
475 name = (char *) alloca (strlen (fname) + pfile->max_include_len
476 + 2 + INCLUDE_LEN_FUDGE);
477 for (path = CPP_OPTION (pfile, quote_include); path; path = path->next)
478 {
479 memcpy (name, path->name, path->nlen);
480 name[path->nlen] = '/';
481 strcpy (&name[path->nlen+1], fname);
482 _cpp_simplify_pathname (name);
483 if (CPP_OPTION (pfile, remap))
484 name = remap_filename (pfile, name, path);
485
486 nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) name);
487 if (nd && nd->value)
488 return 1;
489 }
490 return 0;
491 }
492
493 /* Search for include file FNAME in the include chain starting at
494 SEARCH_START. Return 0 if there is no such file (or it's un-openable),
495 otherwise an include_file structure. */
496
497 static struct include_file *
498 find_include_file (pfile, fname, search_start)
499 cpp_reader *pfile;
500 const char *fname;
501 struct file_name_list *search_start;
502 {
503 struct file_name_list *path;
504 char *name;
505 struct include_file *file;
506
507 if (IS_ABSOLUTE_PATHNAME (fname))
508 return open_file (pfile, fname);
509
510 /* Search directory path for the file. */
511 name = (char *) alloca (strlen (fname) + pfile->max_include_len
512 + 2 + INCLUDE_LEN_FUDGE);
513 for (path = search_start; path; path = path->next)
514 {
515 memcpy (name, path->name, path->nlen);
516 name[path->nlen] = '/';
517 strcpy (&name[path->nlen+1], fname);
518 _cpp_simplify_pathname (name);
519 if (CPP_OPTION (pfile, remap))
520 name = remap_filename (pfile, name, path);
521
522 file = open_file (pfile, name);
523 if (file)
524 {
525 file->foundhere = path;
526 return file;
527 }
528 }
529 return 0;
530 }
531
532 /* Not everyone who wants to set system-header-ness on a buffer can
533 see the details of a buffer. This is an exported interface because
534 fix-header needs it. */
535 void
536 cpp_make_system_header (pfile, syshdr, externc)
537 cpp_reader *pfile;
538 int syshdr, externc;
539 {
540 int flags = 0;
541
542 /* 1 = system header, 2 = system header to be treated as C. */
543 if (syshdr)
544 flags = 1 + (externc != 0);
545 pfile->buffer->sysp = flags;
546 _cpp_do_file_change (pfile, FC_RENAME, pfile->buffer->nominal_fname,
547 pfile->buffer->lineno);
548 }
549
550 /* Report on all files that might benefit from a multiple include guard.
551 Triggered by -H. */
552 void
553 _cpp_report_missing_guards (pfile)
554 cpp_reader *pfile;
555 {
556 int banner = 0;
557 splay_tree_foreach (pfile->all_include_files, report_missing_guard,
558 (PTR) &banner);
559 }
560
561 static int
562 report_missing_guard (n, b)
563 splay_tree_node n;
564 void *b;
565 {
566 struct include_file *f = (struct include_file *) n->value;
567 int *bannerp = (int *)b;
568
569 if (f && f->cmacro == 0 && f->include_count == 1)
570 {
571 if (*bannerp == 0)
572 {
573 fputs (_("Multiple include guards may be useful for:\n"), stderr);
574 *bannerp = 1;
575 }
576 fputs (f->name, stderr);
577 putc ('\n', stderr);
578 }
579 return 0;
580 }
581
582 void
583 _cpp_execute_include (pfile, header, no_reinclude, include_next)
584 cpp_reader *pfile;
585 const cpp_token *header;
586 int no_reinclude;
587 int include_next;
588 {
589 struct file_name_list *search_start = 0;
590 unsigned int len = header->val.str.len;
591 unsigned int angle_brackets = header->type == CPP_HEADER_NAME;
592 struct include_file *inc;
593 char *fname;
594 int print_dep;
595
596 /* Help protect #include or similar from recursion. */
597 if (pfile->buffer_stack_depth >= CPP_STACK_MAX)
598 {
599 cpp_fatal (pfile, "#include nested too deeply");
600 return;
601 }
602
603 /* Check we've tidied up #include before entering the buffer. */
604 if (pfile->context->prev)
605 {
606 cpp_ice (pfile, "attempt to push file buffer with contexts stacked");
607 return;
608 }
609
610 /* For #include_next, skip in the search path past the dir in which
611 the current file was found. If this is the last directory in the
612 search path, don't include anything. If the current file was
613 specified with an absolute path, use the normal search logic. If
614 this is the primary source file, use the normal search logic and
615 generate a warning. */
616 if (include_next)
617 {
618 if (! pfile->buffer->prev)
619 cpp_warning (pfile, "#include_next in primary source file");
620 else
621 {
622 if (pfile->buffer->inc->foundhere)
623 {
624 search_start = pfile->buffer->inc->foundhere->next;
625 if (! search_start)
626 return;
627 }
628 }
629 }
630
631 fname = alloca (len + 1);
632 memcpy (fname, header->val.str.text, len);
633 fname[len] = '\0';
634
635 if (!search_start)
636 {
637 if (angle_brackets)
638 search_start = CPP_OPTION (pfile, bracket_include);
639 else if (CPP_OPTION (pfile, ignore_srcdir))
640 search_start = CPP_OPTION (pfile, quote_include);
641 else
642 search_start = CPP_BUFFER (pfile)->actual_dir;
643
644 if (!search_start)
645 {
646 cpp_error (pfile, "No include path in which to find %s", fname);
647 return;
648 }
649 }
650
651 inc = find_include_file (pfile, fname, search_start);
652 if (inc)
653 {
654 if (angle_brackets)
655 pfile->system_include_depth++;
656
657 stack_include_file (pfile, inc);
658
659 if (! DO_NOT_REREAD (inc))
660 {
661 if (no_reinclude)
662 _cpp_never_reread (inc);
663
664 /* Handle -H option. */
665 if (CPP_OPTION (pfile, print_include_names))
666 {
667 cpp_buffer *fp = CPP_BUFFER (pfile);
668 while ((fp = CPP_PREV_BUFFER (fp)) != NULL)
669 putc ('.', stderr);
670 fprintf (stderr, " %s\n", inc->name);
671 }
672 }
673
674 return;
675 }
676
677 /* We will try making the RHS pfile->buffer->sysp after 3.0. */
678 print_dep = CPP_PRINT_DEPS(pfile) > (angle_brackets
679 || pfile->system_include_depth);
680 if (CPP_OPTION (pfile, print_deps_missing_files) && print_dep)
681 {
682 if (!angle_brackets || IS_ABSOLUTE_PATHNAME (fname))
683 deps_add_dep (pfile->deps, fname);
684 else
685 {
686 char *p;
687 struct file_name_list *ptr;
688 int len;
689
690 /* If requested as a system header, assume it belongs in
691 the first system header directory. */
692 if (CPP_OPTION (pfile, bracket_include))
693 ptr = CPP_OPTION (pfile, bracket_include);
694 else
695 ptr = CPP_OPTION (pfile, quote_include);
696
697 len = strlen (ptr->name);
698 p = (char *) alloca (len + strlen (fname) + 2);
699 if (len)
700 {
701 memcpy (p, ptr->name, len);
702 p[len++] = '/';
703 }
704 strcpy (p + len, fname);
705 _cpp_simplify_pathname (p);
706 deps_add_dep (pfile->deps, p);
707 }
708 }
709 /* If -M was specified, and this header file won't be added to
710 the dependency list, then don't count this as an error,
711 because we can still produce correct output. Otherwise, we
712 can't produce correct output, because there may be
713 dependencies we need inside the missing file, and we don't
714 know what directory this missing file exists in. */
715 else if (CPP_PRINT_DEPS (pfile) && ! print_dep)
716 cpp_warning (pfile, "No include path in which to find %s", fname);
717 else
718 cpp_error_from_errno (pfile, fname);
719 }
720
721 /* Locate file F, and determine whether it is newer than PFILE. Return -1,
722 if F cannot be located or dated, 1, if it is newer and 0 if older. */
723 int
724 _cpp_compare_file_date (pfile, f)
725 cpp_reader *pfile;
726 const cpp_token *f;
727 {
728 unsigned int len = f->val.str.len;
729 char *fname;
730 struct file_name_list *search_start;
731 struct include_file *inc;
732
733 if (f->type == CPP_HEADER_NAME)
734 search_start = CPP_OPTION (pfile, bracket_include);
735 else if (CPP_OPTION (pfile, ignore_srcdir))
736 search_start = CPP_OPTION (pfile, quote_include);
737 else
738 search_start = CPP_BUFFER (pfile)->actual_dir;
739
740 fname = alloca (len + 1);
741 memcpy (fname, f->val.str.text, len);
742 fname[len] = '\0';
743 inc = find_include_file (pfile, fname, search_start);
744
745 if (!inc)
746 return -1;
747 if (inc->fd > 0)
748 {
749 close (inc->fd);
750 inc->fd = -1;
751 }
752
753 return inc->st.st_mtime > CPP_BUFFER (pfile)->inc->st.st_mtime;
754 }
755
756
757 /* Push an input buffer and load it up with the contents of FNAME.
758 If FNAME is "" or NULL, read standard input. */
759 int
760 _cpp_read_file (pfile, fname)
761 cpp_reader *pfile;
762 const char *fname;
763 {
764 struct include_file *f;
765
766 if (fname == NULL)
767 fname = "";
768
769 f = open_file (pfile, fname);
770
771 if (f == NULL)
772 {
773 cpp_error_from_errno (pfile, fname);
774 return 0;
775 }
776
777 stack_include_file (pfile, f);
778 return 1;
779 }
780
781 /* Do appropriate cleanup when a file buffer is popped off the input
782 stack. */
783 void
784 _cpp_pop_file_buffer (pfile, buf)
785 cpp_reader *pfile;
786 cpp_buffer *buf;
787 {
788 struct include_file *inc = buf->inc;
789
790 if (pfile->system_include_depth)
791 pfile->system_include_depth--;
792 if (pfile->include_depth)
793 pfile->include_depth--;
794
795 /* Record the inclusion-preventing macro and its definedness. */
796 if (pfile->mi_state == MI_OUTSIDE && inc->cmacro != NEVER_REREAD)
797 {
798 /* This could be NULL meaning no controlling macro. */
799 inc->cmacro = pfile->mi_cmacro;
800 inc->defined = 1;
801 }
802
803 /* Invalidate control macros in the #including file. */
804 pfile->mi_state = MI_FAILED;
805
806 inc->refcnt--;
807 if (inc->refcnt == 0 && DO_NOT_REREAD (inc))
808 purge_cache (inc);
809 }
810
811 /* The file_name_map structure holds a mapping of file names for a
812 particular directory. This mapping is read from the file named
813 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
814 map filenames on a file system with severe filename restrictions,
815 such as DOS. The format of the file name map file is just a series
816 of lines with two tokens on each line. The first token is the name
817 to map, and the second token is the actual name to use. */
818
819 struct file_name_map
820 {
821 struct file_name_map *map_next;
822 char *map_from;
823 char *map_to;
824 };
825
826 #define FILE_NAME_MAP_FILE "header.gcc"
827
828 /* Read a space delimited string of unlimited length from a stdio
829 file. */
830
831 static char *
832 read_filename_string (ch, f)
833 int ch;
834 FILE *f;
835 {
836 char *alloc, *set;
837 int len;
838
839 len = 20;
840 set = alloc = xmalloc (len + 1);
841 if (! is_space(ch))
842 {
843 *set++ = ch;
844 while ((ch = getc (f)) != EOF && ! is_space(ch))
845 {
846 if (set - alloc == len)
847 {
848 len *= 2;
849 alloc = xrealloc (alloc, len + 1);
850 set = alloc + len / 2;
851 }
852 *set++ = ch;
853 }
854 }
855 *set = '\0';
856 ungetc (ch, f);
857 return alloc;
858 }
859
860 /* This structure holds a linked list of file name maps, one per directory. */
861
862 struct file_name_map_list
863 {
864 struct file_name_map_list *map_list_next;
865 char *map_list_name;
866 struct file_name_map *map_list_map;
867 };
868
869 /* Read the file name map file for DIRNAME. */
870
871 static struct file_name_map *
872 read_name_map (pfile, dirname)
873 cpp_reader *pfile;
874 const char *dirname;
875 {
876 register struct file_name_map_list *map_list_ptr;
877 char *name;
878 FILE *f;
879
880 /* Check the cache of directories, and mappings in their remap file. */
881 for (map_list_ptr = CPP_OPTION (pfile, map_list); map_list_ptr;
882 map_list_ptr = map_list_ptr->map_list_next)
883 if (! strcmp (map_list_ptr->map_list_name, dirname))
884 return map_list_ptr->map_list_map;
885
886 map_list_ptr = ((struct file_name_map_list *)
887 xmalloc (sizeof (struct file_name_map_list)));
888 map_list_ptr->map_list_name = xstrdup (dirname);
889
890 /* The end of the list ends in NULL. */
891 map_list_ptr->map_list_map = NULL;
892
893 name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
894 strcpy (name, dirname);
895 if (*dirname)
896 strcat (name, "/");
897 strcat (name, FILE_NAME_MAP_FILE);
898 f = fopen (name, "r");
899
900 /* Silently return NULL if we cannot open. */
901 if (f)
902 {
903 int ch;
904 int dirlen = strlen (dirname);
905
906 while ((ch = getc (f)) != EOF)
907 {
908 char *from, *to;
909 struct file_name_map *ptr;
910
911 if (is_space(ch))
912 continue;
913 from = read_filename_string (ch, f);
914 while ((ch = getc (f)) != EOF && is_hspace(ch))
915 ;
916 to = read_filename_string (ch, f);
917
918 ptr = ((struct file_name_map *)
919 xmalloc (sizeof (struct file_name_map)));
920 ptr->map_from = from;
921
922 /* Make the real filename absolute. */
923 if (IS_ABSOLUTE_PATHNAME (to))
924 ptr->map_to = to;
925 else
926 {
927 ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
928 strcpy (ptr->map_to, dirname);
929 ptr->map_to[dirlen] = '/';
930 strcpy (ptr->map_to + dirlen + 1, to);
931 free (to);
932 }
933
934 ptr->map_next = map_list_ptr->map_list_map;
935 map_list_ptr->map_list_map = ptr;
936
937 while ((ch = getc (f)) != '\n')
938 if (ch == EOF)
939 break;
940 }
941 fclose (f);
942 }
943
944 /* Add this information to the cache. */
945 map_list_ptr->map_list_next = CPP_OPTION (pfile, map_list);
946 CPP_OPTION (pfile, map_list) = map_list_ptr;
947
948 return map_list_ptr->map_list_map;
949 }
950
951 /* Remap NAME based on the file_name_map (if any) for LOC. */
952
953 static char *
954 remap_filename (pfile, name, loc)
955 cpp_reader *pfile;
956 char *name;
957 struct file_name_list *loc;
958 {
959 struct file_name_map *map;
960 const char *from, *p;
961 char *dir;
962
963 if (! loc->name_map)
964 {
965 loc->name_map = read_name_map (pfile, loc->name ? loc->name : ".");
966 if (! loc->name_map)
967 return name;
968 }
969
970 from = name + strlen (loc->name) + 1;
971
972 for (map = loc->name_map; map; map = map->map_next)
973 if (!strcmp (map->map_from, from))
974 return map->map_to;
975
976 /* Try to find a mapping file for the particular directory we are
977 looking in. Thus #include <sys/types.h> will look up sys/types.h
978 in /usr/include/header.gcc and look up types.h in
979 /usr/include/sys/header.gcc. */
980 p = strrchr (name, '/');
981 if (!p)
982 return name;
983
984 /* We know p != name as absolute paths don't call remap_filename. */
985 if (p == name)
986 cpp_ice (pfile, "absolute file name in remap_filename");
987
988 dir = (char *) alloca (p - name + 1);
989 memcpy (dir, name, p - name);
990 dir[p - name] = '\0';
991 from = p + 1;
992
993 for (map = read_name_map (pfile, dir); map; map = map->map_next)
994 if (! strcmp (map->map_from, from))
995 return map->map_to;
996
997 return name;
998 }
999
1000 /* Given a path FNAME, extract the directory component and place it
1001 onto the actual_dirs list. Return a pointer to the allocated
1002 file_name_list structure. These structures are used to implement
1003 current-directory "" include searching. */
1004
1005 static struct file_name_list *
1006 actual_directory (pfile, fname)
1007 cpp_reader *pfile;
1008 const char *fname;
1009 {
1010 char *last_slash, *dir;
1011 size_t dlen;
1012 struct file_name_list *x;
1013
1014 dir = xstrdup (fname);
1015 last_slash = strrchr (dir, '/');
1016 if (last_slash)
1017 {
1018 if (last_slash == dir)
1019 {
1020 dlen = 1;
1021 last_slash[1] = '\0';
1022 }
1023 else
1024 {
1025 dlen = last_slash - dir;
1026 *last_slash = '\0';
1027 }
1028 }
1029 else
1030 {
1031 free (dir);
1032 dir = xstrdup (".");
1033 dlen = 1;
1034 }
1035
1036 if (dlen > pfile->max_include_len)
1037 pfile->max_include_len = dlen;
1038
1039 for (x = pfile->actual_dirs; x; x = x->alloc)
1040 if (!strcmp (x->name, dir))
1041 {
1042 free (dir);
1043 return x;
1044 }
1045
1046 /* Not found, make a new one. */
1047 x = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1048 x->name = dir;
1049 x->nlen = dlen;
1050 x->next = CPP_OPTION (pfile, quote_include);
1051 x->alloc = pfile->actual_dirs;
1052 x->sysp = pfile->buffer->sysp;
1053 x->name_map = NULL;
1054
1055 pfile->actual_dirs = x;
1056 return x;
1057 }
1058
1059 /* Simplify a path name in place, deleting redundant components. This
1060 reduces OS overhead and guarantees that equivalent paths compare
1061 the same (modulo symlinks).
1062
1063 Transforms made:
1064 foo/bar/../quux foo/quux
1065 foo/./bar foo/bar
1066 foo//bar foo/bar
1067 /../quux /quux
1068 //quux //quux (POSIX allows leading // as a namespace escape)
1069
1070 Guarantees no trailing slashes. All transforms reduce the length
1071 of the string.
1072 */
1073 void
1074 _cpp_simplify_pathname (path)
1075 char *path;
1076 {
1077 char *from, *to;
1078 char *base;
1079 int absolute = 0;
1080
1081 #if defined (HAVE_DOS_BASED_FILE_SYSTEM)
1082 /* Convert all backslashes to slashes. */
1083 for (from = path; *from; from++)
1084 if (*from == '\\') *from = '/';
1085
1086 /* Skip over leading drive letter if present. */
1087 if (ISALPHA (path[0]) && path[1] == ':')
1088 from = to = &path[2];
1089 else
1090 from = to = path;
1091 #else
1092 from = to = path;
1093 #endif
1094
1095 /* Remove redundant initial /s. */
1096 if (*from == '/')
1097 {
1098 absolute = 1;
1099 to++;
1100 from++;
1101 if (*from == '/')
1102 {
1103 if (*++from == '/')
1104 /* 3 or more initial /s are equivalent to 1 /. */
1105 while (*++from == '/');
1106 else
1107 /* On some hosts // differs from /; Posix allows this. */
1108 to++;
1109 }
1110 }
1111 base = to;
1112
1113 for (;;)
1114 {
1115 while (*from == '/')
1116 from++;
1117
1118 if (from[0] == '.' && from[1] == '/')
1119 from += 2;
1120 else if (from[0] == '.' && from[1] == '\0')
1121 goto done;
1122 else if (from[0] == '.' && from[1] == '.' && from[2] == '/')
1123 {
1124 if (base == to)
1125 {
1126 if (absolute)
1127 from += 3;
1128 else
1129 {
1130 *to++ = *from++;
1131 *to++ = *from++;
1132 *to++ = *from++;
1133 base = to;
1134 }
1135 }
1136 else
1137 {
1138 to -= 2;
1139 while (to > base && *to != '/') to--;
1140 if (*to == '/')
1141 to++;
1142 from += 3;
1143 }
1144 }
1145 else if (from[0] == '.' && from[1] == '.' && from[2] == '\0')
1146 {
1147 if (base == to)
1148 {
1149 if (!absolute)
1150 {
1151 *to++ = *from++;
1152 *to++ = *from++;
1153 }
1154 }
1155 else
1156 {
1157 to -= 2;
1158 while (to > base && *to != '/') to--;
1159 if (*to == '/')
1160 to++;
1161 }
1162 goto done;
1163 }
1164 else
1165 /* Copy this component and trailing /, if any. */
1166 while ((*to++ = *from++) != '/')
1167 {
1168 if (!to[-1])
1169 {
1170 to--;
1171 goto done;
1172 }
1173 }
1174
1175 }
1176
1177 done:
1178 /* Trim trailing slash */
1179 if (to[0] == '/' && (!absolute || to > path+1))
1180 to--;
1181
1182 /* Change the empty string to "." so that stat() on the result
1183 will always work. */
1184 if (to == path)
1185 *to++ = '.';
1186
1187 *to = '\0';
1188
1189 return;
1190 }