cppfiles.c (stack_include_file): Push zero-length buffers in case of failure.
[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 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 static struct file_name_map *read_name_map
67 PARAMS ((cpp_reader *, const char *));
68 static char *read_filename_string PARAMS ((int, FILE *));
69 static char *remap_filename PARAMS ((cpp_reader *, char *,
70 struct file_name_list *));
71 static struct file_name_list *actual_directory
72 PARAMS ((cpp_reader *, const char *));
73 static struct include_file *find_include_file
74 PARAMS ((cpp_reader *, const char *,
75 struct file_name_list *));
76 static struct include_file *open_file PARAMS ((cpp_reader *, const char *));
77 static void read_include_file PARAMS ((cpp_reader *, struct include_file *));
78 static void stack_include_file PARAMS ((cpp_reader *, struct include_file *));
79 static void purge_cache PARAMS ((struct include_file *));
80 static void destroy_include_file_node PARAMS ((splay_tree_value));
81 static int report_missing_guard PARAMS ((splay_tree_node, void *));
82
83 #if 0
84 static void hack_vms_include_specification PARAMS ((char *));
85 #endif
86
87 /* We use a splay tree to store information about all the include
88 files seen in this compilation. The key of each tree node is the
89 physical path to the file. The value is 0 if the file does not
90 exist, or a struct include_file pointer. */
91
92 static void
93 destroy_include_file_node (v)
94 splay_tree_value v;
95 {
96 struct include_file *f = (struct include_file *)v;
97 if (f)
98 {
99 purge_cache (f);
100 free (f); /* The tree is registered with free to free f->name. */
101 }
102 }
103
104 void
105 _cpp_init_includes (pfile)
106 cpp_reader *pfile;
107 {
108 pfile->all_include_files
109 = splay_tree_new ((splay_tree_compare_fn) strcmp,
110 (splay_tree_delete_key_fn) free,
111 destroy_include_file_node);
112 }
113
114 void
115 _cpp_cleanup_includes (pfile)
116 cpp_reader *pfile;
117 {
118 splay_tree_delete (pfile->all_include_files);
119 }
120
121 /* Given a file name, look it up in the cache; if there is no entry,
122 create one with a non-NULL value (regardless of success in opening
123 the file). If the file doesn't exist or is inaccessible, this
124 entry is flagged so we don't attempt to open it again in the
125 future. If the file isn't open, open it.
126
127 Returns an include_file structure with an open file descriptor on
128 success, or NULL on failure. */
129
130 static struct include_file *
131 open_file (pfile, filename)
132 cpp_reader *pfile;
133 const char *filename;
134 {
135 splay_tree_node nd;
136 struct include_file *file;
137
138 nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) filename);
139
140 if (nd)
141 {
142 file = (struct include_file *) nd->value;
143
144 /* Don't retry opening if we failed previously. */
145 if (file->fd == -2)
146 return 0;
147
148 /* Don't reopen an idempotent file. */
149 if (DO_NOT_REREAD (file))
150 return file;
151
152 /* Don't reopen one which is already loaded. */
153 if (file->buffer != NULL)
154 return file;
155 }
156 else
157 {
158 file = xcnew (struct include_file);
159 file->name = xstrdup (filename);
160 splay_tree_insert (pfile->all_include_files,
161 (splay_tree_key) file->name,
162 (splay_tree_value) file);
163 }
164
165 /* We used to open files in nonblocking mode, but that caused more
166 problems than it solved. Do take care not to acquire a
167 controlling terminal by mistake (this can't happen on sane
168 systems, but paranoia is a virtue).
169
170 Use the three-argument form of open even though we aren't
171 specifying O_CREAT, to defend against broken system headers.
172
173 O_BINARY tells some runtime libraries (notably DJGPP) not to do
174 newline translation; we can handle DOS line breaks just fine
175 ourselves.
176
177 Special case: the empty string is translated to stdin. */
178
179 if (filename[0] == '\0')
180 file->fd = 0;
181 else
182 file->fd = open (filename, O_RDONLY | O_NOCTTY | O_BINARY, 0666);
183
184 if (file->fd != -1 && fstat (file->fd, &file->st) == 0)
185 {
186 /* Mark a regular, zero-length file never-reread now. */
187 if (S_ISREG (file->st.st_mode) && file->st.st_size == 0)
188 {
189 file->cmacro = NEVER_REREAD;
190 close (file->fd);
191 file->fd = -1;
192 }
193
194 return file;
195 }
196
197 /* Don't issue an error message if the file doesn't exist. */
198 if (errno != ENOENT && errno != ENOTDIR)
199 cpp_error_from_errno (pfile, filename);
200
201 /* Create a negative node for this path, and return null. */
202 file->fd = -2;
203
204 return 0;
205 }
206
207 /* Place the file referenced by INC into a new buffer on PFILE's
208 stack. If there are errors, or the file should not be re-included,
209 a null buffer is pushed. */
210
211 static void
212 stack_include_file (pfile, inc)
213 cpp_reader *pfile;
214 struct include_file *inc;
215 {
216 const char *filename = 0;
217 unsigned int lineno = 0;
218 cpp_buffer *fp;
219
220 if (pfile->buffer)
221 {
222 filename = pfile->buffer->nominal_fname;
223 lineno = pfile->buffer->lineno;
224 }
225
226 /* Not in cache? */
227 if (! inc->buffer)
228 read_include_file (pfile, inc);
229
230 /* Push a null buffer. */
231 fp = cpp_push_buffer (pfile, NULL, 0);
232 fp->inc = inc;
233 fp->nominal_fname = inc->name;
234 fp->buf = inc->buffer;
235 fp->rlimit = fp->buf;
236 if (! DO_NOT_REREAD (inc))
237 fp->rlimit += inc->st.st_size;
238 fp->cur = fp->buf;
239 fp->line_base = fp->buf;
240 fp->lineno = 0; /* For _cpp_do_file_change. */
241 fp->inc->refcnt++;
242
243 /* The ->actual_dir field is only used when ignore_srcdir is not in effect;
244 see do_include */
245 if (!CPP_OPTION (pfile, ignore_srcdir))
246 fp->actual_dir = actual_directory (pfile, inc->name);
247
248 /* Initialise controlling macro state. */
249 pfile->mi_state = MI_OUTSIDE;
250 pfile->mi_cmacro = 0;
251 pfile->include_depth++;
252 pfile->input_stack_listing_current = 0;
253
254 _cpp_do_file_change (pfile, FC_ENTER, filename, lineno);
255
256 fp->lineno = 1;
257 }
258
259 /* Read the file referenced by INC into the file cache.
260
261 If fd points to a plain file, we might be able to mmap it; we can
262 definitely allocate the buffer all at once. If fd is a pipe or
263 terminal, we can't do either. If fd is something weird, like a
264 block device or a directory, we don't want to read it at all.
265
266 Unfortunately, different systems use different st.st_mode values
267 for pipes: some have S_ISFIFO, some S_ISSOCK, some are buggy and
268 zero the entire struct stat except a couple fields. Hence we don't
269 even try to figure out what something is, except for plain files,
270 directories, and block devices.
271
272 FIXME: Flush file cache and try again if we run out of memory. */
273
274 static void
275 read_include_file (pfile, inc)
276 cpp_reader *pfile;
277 struct include_file *inc;
278 {
279 ssize_t size, offset, count;
280 U_CHAR *buf;
281 #if MMAP_THRESHOLD
282 static int pagesize = -1;
283 #endif
284
285 if (DO_NOT_REREAD (inc))
286 return;
287
288 if (S_ISREG (inc->st.st_mode))
289 {
290 /* off_t might have a wider range than ssize_t - in other words,
291 the max size of a file might be bigger than the address
292 space. We can't handle a file that large. (Anyone with
293 a single source file bigger than 2GB needs to rethink
294 their coding style.) Some systems (e.g. AIX 4.1) define
295 SSIZE_MAX to be much smaller than the actual range of the
296 type. Use INTTYPE_MAXIMUM unconditionally to ensure this
297 does not bite us. */
298 if (inc->st.st_size > INTTYPE_MAXIMUM (ssize_t))
299 {
300 cpp_error (pfile, "%s is too large", inc->name);
301 goto fail;
302 }
303 size = inc->st.st_size;
304
305 inc->mapped = 0;
306 #if MMAP_THRESHOLD
307 if (pagesize == -1)
308 pagesize = getpagesize ();
309
310 if (size / pagesize >= MMAP_THRESHOLD)
311 {
312 buf = (U_CHAR *) mmap (0, size, PROT_READ, MAP_PRIVATE, inc->fd, 0);
313 if (buf == (U_CHAR *)-1)
314 goto perror_fail;
315 inc->mapped = 1;
316 }
317 else
318 #endif
319 {
320 buf = (U_CHAR *) xmalloc (size);
321 offset = 0;
322 while (offset < size)
323 {
324 count = read (inc->fd, buf + offset, size - offset);
325 if (count < 0)
326 goto perror_fail;
327 if (count == 0)
328 {
329 cpp_warning (pfile, "%s is shorter than expected", inc->name);
330 break;
331 }
332 offset += count;
333 }
334 }
335 }
336 else if (S_ISBLK (inc->st.st_mode))
337 {
338 cpp_error (pfile, "%s is a block device", inc->name);
339 goto fail;
340 }
341 else if (S_ISDIR (inc->st.st_mode))
342 {
343 cpp_error (pfile, "%s is a directory", inc->name);
344 goto fail;
345 }
346 else
347 {
348 /* 8 kilobytes is a sensible starting size. It ought to be
349 bigger than the kernel pipe buffer, and it's definitely
350 bigger than the majority of C source files. */
351 size = 8 * 1024;
352
353 buf = (U_CHAR *) xmalloc (size);
354 offset = 0;
355 while ((count = read (inc->fd, buf + offset, size - offset)) > 0)
356 {
357 offset += count;
358 if (offset == size)
359 buf = xrealloc (buf, (size *= 2));
360 }
361 if (count < 0)
362 goto perror_fail;
363
364 if (offset < size)
365 buf = xrealloc (buf, offset);
366 inc->st.st_size = offset;
367 }
368
369 close (inc->fd);
370 inc->buffer = buf;
371 inc->fd = -1;
372 return;
373
374 perror_fail:
375 cpp_error_from_errno (pfile, inc->name);
376 fail:
377 /* Do not try to read this file again. */
378 close (inc->fd);
379 inc->fd = -1;
380 inc->cmacro = NEVER_REREAD;
381 return;
382 }
383
384 static void
385 purge_cache (inc)
386 struct include_file *inc;
387 {
388 if (inc->buffer)
389 {
390 #if MMAP_THRESHOLD
391 if (inc->mapped)
392 munmap ((PTR) inc->buffer, inc->st.st_size);
393 else
394 #endif
395 free ((PTR) inc->buffer);
396 inc->buffer = NULL;
397 }
398 }
399
400 /* Return 1 if the file named by FNAME has been included before in
401 any context, 0 otherwise. */
402 int
403 cpp_included (pfile, fname)
404 cpp_reader *pfile;
405 const char *fname;
406 {
407 struct file_name_list *path;
408 char *name;
409 splay_tree_node nd;
410
411 if (fname[0] == '/')
412 {
413 /* Just look it up. */
414 nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) fname);
415 return (nd && nd->value);
416 }
417
418 /* Search directory path for the file. */
419 name = (char *) alloca (strlen (fname) + pfile->max_include_len
420 + 2 + INCLUDE_LEN_FUDGE);
421 for (path = CPP_OPTION (pfile, quote_include); path; path = path->next)
422 {
423 memcpy (name, path->name, path->nlen);
424 name[path->nlen] = '/';
425 strcpy (&name[path->nlen+1], fname);
426 _cpp_simplify_pathname (name);
427 if (CPP_OPTION (pfile, remap))
428 name = remap_filename (pfile, name, path);
429
430 nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) name);
431 if (nd && nd->value)
432 return 1;
433 }
434 return 0;
435 }
436
437 /* Search for include file FNAME in the include chain starting at
438 SEARCH_START. Return 0 if there is no such file (or it's un-openable),
439 otherwise an include_file structure. */
440
441 static struct include_file *
442 find_include_file (pfile, fname, search_start)
443 cpp_reader *pfile;
444 const char *fname;
445 struct file_name_list *search_start;
446 {
447 struct file_name_list *path;
448 char *name;
449 struct include_file *file;
450
451 if (fname[0] == '/')
452 return open_file (pfile, fname);
453
454 /* Search directory path for the file. */
455 name = (char *) alloca (strlen (fname) + pfile->max_include_len
456 + 2 + INCLUDE_LEN_FUDGE);
457 for (path = search_start; path; path = path->next)
458 {
459 memcpy (name, path->name, path->nlen);
460 name[path->nlen] = '/';
461 strcpy (&name[path->nlen+1], fname);
462 _cpp_simplify_pathname (name);
463 if (CPP_OPTION (pfile, remap))
464 name = remap_filename (pfile, name, path);
465
466 file = open_file (pfile, name);
467 if (file)
468 {
469 file->sysp = path->sysp;
470 file->foundhere = path;
471 return file;
472 }
473 }
474 return 0;
475 }
476
477 /* #line uses this to save artificial file names. We have to stat the
478 file because an all_include_files entry is always either + or -,
479 there's no 'I don't know' value. */
480 const char *
481 _cpp_fake_include (pfile, fname)
482 cpp_reader *pfile;
483 const char *fname;
484 {
485 splay_tree_node nd;
486 struct include_file *file;
487 char *name;
488
489 file = find_include_file (pfile, fname, CPP_OPTION (pfile, quote_include));
490 if (file)
491 {
492 if (file->fd > 0)
493 {
494 close (file->fd);
495 file->fd = -1;
496 }
497 return file->name;
498 }
499
500 name = xstrdup (fname);
501 _cpp_simplify_pathname (name);
502
503 /* We cannot just blindly insert a node, because there's still the
504 chance that the node already exists but isn't on the search path. */
505 nd = splay_tree_lookup (pfile->all_include_files, (splay_tree_key) name);
506 if (nd)
507 {
508 free (name);
509 return (const char *) nd->key;
510 }
511
512 file = xcnew (struct include_file);
513 file->name = name;
514 file->fd = -2;
515 splay_tree_insert (pfile->all_include_files, (splay_tree_key) name,
516 (splay_tree_value) file);
517
518 return file->name;
519 }
520
521 /* Not everyone who wants to set system-header-ness on a buffer can
522 see the details of struct include_file. This is an exported interface
523 because fix-header needs it. */
524 void
525 cpp_make_system_header (pfile, syshdr, externc)
526 cpp_reader *pfile;
527 int syshdr, externc;
528 {
529 int flags = 0;
530
531 /* 1 = system header, 2 = system header to be treated as C. */
532 if (syshdr)
533 flags = 1 + (externc != 0);
534 pfile->buffer->inc->sysp = flags;
535 }
536
537 /* Report on all files that might benefit from a multiple include guard.
538 Triggered by -H. */
539 void
540 _cpp_report_missing_guards (pfile)
541 cpp_reader *pfile;
542 {
543 int banner = 0;
544 splay_tree_foreach (pfile->all_include_files, report_missing_guard,
545 (PTR) &banner);
546 }
547
548 static int
549 report_missing_guard (n, b)
550 splay_tree_node n;
551 void *b;
552 {
553 struct include_file *f = (struct include_file *) n->value;
554 int *bannerp = (int *)b;
555
556 if (f && f->cmacro == 0 && f->include_count == 1)
557 {
558 if (*bannerp == 0)
559 {
560 fputs (_("Multiple include guards may be useful for:\n"), stderr);
561 *bannerp = 1;
562 }
563 fputs (f->name, stderr);
564 putc ('\n', stderr);
565 }
566 return 0;
567 }
568
569 #define PRINT_THIS_DEP(p, b) (CPP_PRINT_DEPS(p) > (b||p->system_include_depth))
570 void
571 _cpp_execute_include (pfile, header, no_reinclude, search_start)
572 cpp_reader *pfile;
573 const cpp_token *header;
574 int no_reinclude;
575 struct file_name_list *search_start;
576 {
577 unsigned int len = header->val.str.len;
578 unsigned int angle_brackets = header->type == CPP_HEADER_NAME;
579 struct include_file *inc;
580 char *fname;
581
582 /* Help protect #include or similar from recursion. */
583 if (pfile->buffer_stack_depth >= CPP_STACK_MAX)
584 {
585 cpp_fatal (pfile, "#include nested too deeply");
586 return;
587 }
588
589 /* Check we've tidied up #include before entering the buffer. */
590 if (pfile->context->prev)
591 {
592 cpp_ice (pfile, "attempt to push file buffer with contexts stacked");
593 return;
594 }
595
596 fname = alloca (len + 1);
597 memcpy (fname, header->val.str.text, len);
598 fname[len] = '\0';
599
600 if (!search_start)
601 {
602 if (angle_brackets)
603 search_start = CPP_OPTION (pfile, bracket_include);
604 else if (CPP_OPTION (pfile, ignore_srcdir))
605 search_start = CPP_OPTION (pfile, quote_include);
606 else
607 search_start = CPP_BUFFER (pfile)->actual_dir;
608
609 if (!search_start)
610 {
611 cpp_error (pfile, "No include path in which to find %s", fname);
612 return;
613 }
614 }
615
616 inc = find_include_file (pfile, fname, search_start);
617
618 if (inc)
619 {
620 /* For -M, add the file to the dependencies on its first inclusion. */
621 if (!inc->include_count && PRINT_THIS_DEP (pfile, angle_brackets))
622 deps_add_dep (pfile->deps, inc->name);
623 inc->include_count++;
624
625 /* Actually process the file. */
626 stack_include_file (pfile, inc);
627
628 if (angle_brackets)
629 pfile->system_include_depth++;
630
631 if (! DO_NOT_REREAD (inc))
632 {
633 if (no_reinclude)
634 inc->cmacro = NEVER_REREAD;
635
636 /* Handle -H option. */
637 if (CPP_OPTION (pfile, print_include_names))
638 {
639 cpp_buffer *fp = CPP_BUFFER (pfile);
640 while ((fp = CPP_PREV_BUFFER (fp)) != NULL)
641 putc ('.', stderr);
642 fprintf (stderr, " %s\n", inc->name);
643 }
644 }
645
646 return;
647 }
648
649 if (CPP_OPTION (pfile, print_deps_missing_files)
650 && PRINT_THIS_DEP (pfile, angle_brackets))
651 {
652 if (!angle_brackets)
653 deps_add_dep (pfile->deps, fname);
654 else
655 {
656 char *p;
657 struct file_name_list *ptr;
658 /* If requested as a system header, assume it belongs in
659 the first system header directory. */
660 if (CPP_OPTION (pfile, bracket_include))
661 ptr = CPP_OPTION (pfile, bracket_include);
662 else
663 ptr = CPP_OPTION (pfile, quote_include);
664
665 p = (char *) alloca (strlen (ptr->name)
666 + strlen (fname) + 2);
667 if (*ptr->name != '\0')
668 {
669 strcpy (p, ptr->name);
670 strcat (p, "/");
671 }
672 strcat (p, fname);
673 _cpp_simplify_pathname (p);
674 deps_add_dep (pfile->deps, p);
675 }
676 }
677 /* If -M was specified, and this header file won't be added to
678 the dependency list, then don't count this as an error,
679 because we can still produce correct output. Otherwise, we
680 can't produce correct output, because there may be
681 dependencies we need inside the missing file, and we don't
682 know what directory this missing file exists in. */
683 else if (CPP_PRINT_DEPS (pfile)
684 && ! PRINT_THIS_DEP (pfile, angle_brackets))
685 cpp_warning (pfile, "No include path in which to find %s", fname);
686 else
687 cpp_error_from_errno (pfile, fname);
688 }
689
690 /* Locate file F, and determine whether it is newer than PFILE. Return -1,
691 if F cannot be located or dated, 1, if it is newer and 0 if older. */
692 int
693 _cpp_compare_file_date (pfile, f)
694 cpp_reader *pfile;
695 const cpp_token *f;
696 {
697 unsigned int len = f->val.str.len;
698 char *fname;
699 struct file_name_list *search_start;
700 struct include_file *inc;
701
702 if (f->type == CPP_HEADER_NAME)
703 search_start = CPP_OPTION (pfile, bracket_include);
704 else if (CPP_OPTION (pfile, ignore_srcdir))
705 search_start = CPP_OPTION (pfile, quote_include);
706 else
707 search_start = CPP_BUFFER (pfile)->actual_dir;
708
709 fname = alloca (len + 1);
710 memcpy (fname, f->val.str.text, len);
711 fname[len] = '\0';
712 inc = find_include_file (pfile, fname, search_start);
713
714 if (!inc)
715 return -1;
716 if (inc->fd > 0)
717 {
718 close (inc->fd);
719 inc->fd = -1;
720 }
721
722 return inc->st.st_mtime > CPP_BUFFER (pfile)->inc->st.st_mtime;
723 }
724
725
726 /* Push an input buffer and load it up with the contents of FNAME.
727 If FNAME is "" or NULL, read standard input. */
728 int
729 _cpp_read_file (pfile, fname)
730 cpp_reader *pfile;
731 const char *fname;
732 {
733 struct include_file *f;
734
735 if (fname == NULL)
736 fname = "";
737
738 f = open_file (pfile, fname);
739
740 if (f == NULL)
741 {
742 cpp_error_from_errno (pfile, fname);
743 return 0;
744 }
745
746 stack_include_file (pfile, f);
747 return 1;
748 }
749
750 /* Do appropriate cleanup when a file buffer is popped off the input
751 stack. */
752 void
753 _cpp_pop_file_buffer (pfile, buf)
754 cpp_reader *pfile;
755 cpp_buffer *buf;
756 {
757 struct include_file *inc = buf->inc;
758
759 if (pfile->system_include_depth)
760 pfile->system_include_depth--;
761 if (pfile->include_depth)
762 pfile->include_depth--;
763 pfile->input_stack_listing_current = 0;
764
765 /* Record the inclusion-preventing macro and its definedness. */
766 if (pfile->mi_state == MI_OUTSIDE && inc->cmacro != NEVER_REREAD)
767 {
768 /* This could be NULL meaning no controlling macro. */
769 inc->cmacro = pfile->mi_cmacro;
770 inc->defined = 1;
771 }
772
773 /* Invalidate control macros in the #including file. */
774 pfile->mi_state = MI_FAILED;
775
776 inc->refcnt--;
777 if (inc->refcnt == 0 && DO_NOT_REREAD (inc))
778 purge_cache (inc);
779 }
780
781 /* The file_name_map structure holds a mapping of file names for a
782 particular directory. This mapping is read from the file named
783 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
784 map filenames on a file system with severe filename restrictions,
785 such as DOS. The format of the file name map file is just a series
786 of lines with two tokens on each line. The first token is the name
787 to map, and the second token is the actual name to use. */
788
789 struct file_name_map
790 {
791 struct file_name_map *map_next;
792 char *map_from;
793 char *map_to;
794 };
795
796 #define FILE_NAME_MAP_FILE "header.gcc"
797
798 /* Read a space delimited string of unlimited length from a stdio
799 file. */
800
801 static char *
802 read_filename_string (ch, f)
803 int ch;
804 FILE *f;
805 {
806 char *alloc, *set;
807 int len;
808
809 len = 20;
810 set = alloc = xmalloc (len + 1);
811 if (! is_space(ch))
812 {
813 *set++ = ch;
814 while ((ch = getc (f)) != EOF && ! is_space(ch))
815 {
816 if (set - alloc == len)
817 {
818 len *= 2;
819 alloc = xrealloc (alloc, len + 1);
820 set = alloc + len / 2;
821 }
822 *set++ = ch;
823 }
824 }
825 *set = '\0';
826 ungetc (ch, f);
827 return alloc;
828 }
829
830 /* This structure holds a linked list of file name maps, one per directory. */
831
832 struct file_name_map_list
833 {
834 struct file_name_map_list *map_list_next;
835 char *map_list_name;
836 struct file_name_map *map_list_map;
837 };
838
839 /* Read the file name map file for DIRNAME. */
840
841 static struct file_name_map *
842 read_name_map (pfile, dirname)
843 cpp_reader *pfile;
844 const char *dirname;
845 {
846 register struct file_name_map_list *map_list_ptr;
847 char *name;
848 FILE *f;
849
850 for (map_list_ptr = CPP_OPTION (pfile, map_list); map_list_ptr;
851 map_list_ptr = map_list_ptr->map_list_next)
852 if (! strcmp (map_list_ptr->map_list_name, dirname))
853 return map_list_ptr->map_list_map;
854
855 map_list_ptr = ((struct file_name_map_list *)
856 xmalloc (sizeof (struct file_name_map_list)));
857 map_list_ptr->map_list_name = xstrdup (dirname);
858 map_list_ptr->map_list_map = NULL;
859
860 name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
861 strcpy (name, dirname);
862 if (*dirname)
863 strcat (name, "/");
864 strcat (name, FILE_NAME_MAP_FILE);
865 f = fopen (name, "r");
866 if (!f)
867 map_list_ptr->map_list_map = (struct file_name_map *)-1;
868 else
869 {
870 int ch;
871 int dirlen = strlen (dirname);
872
873 while ((ch = getc (f)) != EOF)
874 {
875 char *from, *to;
876 struct file_name_map *ptr;
877
878 if (is_space(ch))
879 continue;
880 from = read_filename_string (ch, f);
881 while ((ch = getc (f)) != EOF && is_hspace(ch))
882 ;
883 to = read_filename_string (ch, f);
884
885 ptr = ((struct file_name_map *)
886 xmalloc (sizeof (struct file_name_map)));
887 ptr->map_from = from;
888
889 /* Make the real filename absolute. */
890 if (*to == '/')
891 ptr->map_to = to;
892 else
893 {
894 ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
895 strcpy (ptr->map_to, dirname);
896 ptr->map_to[dirlen] = '/';
897 strcpy (ptr->map_to + dirlen + 1, to);
898 free (to);
899 }
900
901 ptr->map_next = map_list_ptr->map_list_map;
902 map_list_ptr->map_list_map = ptr;
903
904 while ((ch = getc (f)) != '\n')
905 if (ch == EOF)
906 break;
907 }
908 fclose (f);
909 }
910
911 map_list_ptr->map_list_next = CPP_OPTION (pfile, map_list);
912 CPP_OPTION (pfile, map_list) = map_list_ptr;
913
914 return map_list_ptr->map_list_map;
915 }
916
917 /* Remap NAME based on the file_name_map (if any) for LOC. */
918
919 static char *
920 remap_filename (pfile, name, loc)
921 cpp_reader *pfile;
922 char *name;
923 struct file_name_list *loc;
924 {
925 struct file_name_map *map;
926 const char *from, *p, *dir;
927
928 if (! loc->name_map)
929 loc->name_map = read_name_map (pfile,
930 loc->name
931 ? loc->name : ".");
932
933 if (loc->name_map == (struct file_name_map *)-1)
934 return name;
935
936 from = name + strlen (loc->name) + 1;
937
938 for (map = loc->name_map; map; map = map->map_next)
939 if (!strcmp (map->map_from, from))
940 return map->map_to;
941
942 /* Try to find a mapping file for the particular directory we are
943 looking in. Thus #include <sys/types.h> will look up sys/types.h
944 in /usr/include/header.gcc and look up types.h in
945 /usr/include/sys/header.gcc. */
946 p = strrchr (name, '/');
947 if (!p)
948 p = name;
949 if (loc && loc->name
950 && strlen (loc->name) == (size_t) (p - name)
951 && !strncmp (loc->name, name, p - name))
952 /* FILENAME is in SEARCHPTR, which we've already checked. */
953 return name;
954
955 if (p == name)
956 {
957 dir = ".";
958 from = name;
959 }
960 else
961 {
962 char * newdir = (char *) alloca (p - name + 1);
963 memcpy (newdir, name, p - name);
964 newdir[p - name] = '\0';
965 dir = newdir;
966 from = p + 1;
967 }
968
969 for (map = read_name_map (pfile, dir); map; map = map->map_next)
970 if (! strcmp (map->map_from, name))
971 return map->map_to;
972
973 return name;
974 }
975
976 /* Given a path FNAME, extract the directory component and place it
977 onto the actual_dirs list. Return a pointer to the allocated
978 file_name_list structure. These structures are used to implement
979 current-directory "" include searching. */
980
981 static struct file_name_list *
982 actual_directory (pfile, fname)
983 cpp_reader *pfile;
984 const char *fname;
985 {
986 char *last_slash, *dir;
987 size_t dlen;
988 struct file_name_list *x;
989
990 dir = xstrdup (fname);
991 last_slash = strrchr (dir, '/');
992 if (last_slash)
993 {
994 if (last_slash == dir)
995 {
996 dlen = 1;
997 last_slash[1] = '\0';
998 }
999 else
1000 {
1001 dlen = last_slash - dir;
1002 *last_slash = '\0';
1003 }
1004 }
1005 else
1006 {
1007 free (dir);
1008 dir = xstrdup (".");
1009 dlen = 1;
1010 }
1011
1012 if (dlen > pfile->max_include_len)
1013 pfile->max_include_len = dlen;
1014
1015 for (x = pfile->actual_dirs; x; x = x->alloc)
1016 if (!strcmp (x->name, dir))
1017 {
1018 free (dir);
1019 return x;
1020 }
1021
1022 /* Not found, make a new one. */
1023 x = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1024 x->name = dir;
1025 x->nlen = dlen;
1026 x->next = CPP_OPTION (pfile, quote_include);
1027 x->alloc = pfile->actual_dirs;
1028 x->sysp = CPP_BUFFER (pfile)->inc->sysp;
1029 x->name_map = NULL;
1030
1031 pfile->actual_dirs = x;
1032 return x;
1033 }
1034
1035 /* Simplify a path name in place, deleting redundant components. This
1036 reduces OS overhead and guarantees that equivalent paths compare
1037 the same (modulo symlinks).
1038
1039 Transforms made:
1040 foo/bar/../quux foo/quux
1041 foo/./bar foo/bar
1042 foo//bar foo/bar
1043 /../quux /quux
1044 //quux //quux (POSIX allows leading // as a namespace escape)
1045
1046 Guarantees no trailing slashes. All transforms reduce the length
1047 of the string.
1048 */
1049 void
1050 _cpp_simplify_pathname (path)
1051 char *path;
1052 {
1053 char *from, *to;
1054 char *base;
1055 int absolute = 0;
1056
1057 #if defined (HAVE_DOS_BASED_FILE_SYSTEM)
1058 /* Convert all backslashes to slashes. */
1059 for (from = path; *from; from++)
1060 if (*from == '\\') *from = '/';
1061
1062 /* Skip over leading drive letter if present. */
1063 if (ISALPHA (path[0]) && path[1] == ':')
1064 from = to = &path[2];
1065 else
1066 from = to = path;
1067 #else
1068 from = to = path;
1069 #endif
1070
1071 /* Remove redundant initial /s. */
1072 if (*from == '/')
1073 {
1074 absolute = 1;
1075 to++;
1076 from++;
1077 if (*from == '/')
1078 {
1079 if (*++from == '/')
1080 /* 3 or more initial /s are equivalent to 1 /. */
1081 while (*++from == '/');
1082 else
1083 /* On some hosts // differs from /; Posix allows this. */
1084 to++;
1085 }
1086 }
1087 base = to;
1088
1089 for (;;)
1090 {
1091 while (*from == '/')
1092 from++;
1093
1094 if (from[0] == '.' && from[1] == '/')
1095 from += 2;
1096 else if (from[0] == '.' && from[1] == '\0')
1097 goto done;
1098 else if (from[0] == '.' && from[1] == '.' && from[2] == '/')
1099 {
1100 if (base == to)
1101 {
1102 if (absolute)
1103 from += 3;
1104 else
1105 {
1106 *to++ = *from++;
1107 *to++ = *from++;
1108 *to++ = *from++;
1109 base = to;
1110 }
1111 }
1112 else
1113 {
1114 to -= 2;
1115 while (to > base && *to != '/') to--;
1116 if (*to == '/')
1117 to++;
1118 from += 3;
1119 }
1120 }
1121 else if (from[0] == '.' && from[1] == '.' && from[2] == '\0')
1122 {
1123 if (base == to)
1124 {
1125 if (!absolute)
1126 {
1127 *to++ = *from++;
1128 *to++ = *from++;
1129 }
1130 }
1131 else
1132 {
1133 to -= 2;
1134 while (to > base && *to != '/') to--;
1135 if (*to == '/')
1136 to++;
1137 }
1138 goto done;
1139 }
1140 else
1141 /* Copy this component and trailing /, if any. */
1142 while ((*to++ = *from++) != '/')
1143 {
1144 if (!to[-1])
1145 {
1146 to--;
1147 goto done;
1148 }
1149 }
1150
1151 }
1152
1153 done:
1154 /* Trim trailing slash */
1155 if (to[0] == '/' && (!absolute || to > path+1))
1156 to--;
1157
1158 /* Change the empty string to "." so that stat() on the result
1159 will always work. */
1160 if (to == path)
1161 *to++ = '.';
1162
1163 *to = '\0';
1164
1165 return;
1166 }
1167
1168 /* It is not clear when this should be used if at all, so I've
1169 disabled it until someone who understands VMS can look at it. */
1170 #if 0
1171
1172 /* Under VMS we need to fix up the "include" specification filename.
1173
1174 Rules for possible conversions
1175
1176 fullname tried paths
1177
1178 name name
1179 ./dir/name [.dir]name
1180 /dir/name dir:name
1181 /name [000000]name, name
1182 dir/name dir:[000000]name, dir:name, dir/name
1183 dir1/dir2/name dir1:[dir2]name, dir1:[000000.dir2]name
1184 path:/name path:[000000]name, path:name
1185 path:/dir/name path:[000000.dir]name, path:[dir]name
1186 path:dir/name path:[dir]name
1187 [path]:[dir]name [path.dir]name
1188 path/[dir]name [path.dir]name
1189
1190 The path:/name input is constructed when expanding <> includes. */
1191
1192
1193 static void
1194 hack_vms_include_specification (fullname)
1195 char *fullname;
1196 {
1197 register char *basename, *unixname, *local_ptr, *first_slash;
1198 int f, check_filename_before_returning, must_revert;
1199 char Local[512];
1200
1201 check_filename_before_returning = 0;
1202 must_revert = 0;
1203 /* See if we can find a 1st slash. If not, there's no path information. */
1204 first_slash = strchr (fullname, '/');
1205 if (first_slash == 0)
1206 return 0; /* Nothing to do!!! */
1207
1208 /* construct device spec if none given. */
1209
1210 if (strchr (fullname, ':') == 0)
1211 {
1212
1213 /* If fullname has a slash, take it as device spec. */
1214
1215 if (first_slash == fullname)
1216 {
1217 first_slash = strchr (fullname + 1, '/'); /* 2nd slash ? */
1218 if (first_slash)
1219 *first_slash = ':'; /* make device spec */
1220 for (basename = fullname; *basename != 0; basename++)
1221 *basename = *(basename+1); /* remove leading slash */
1222 }
1223 else if ((first_slash[-1] != '.') /* keep ':/', './' */
1224 && (first_slash[-1] != ':')
1225 && (first_slash[-1] != ']')) /* or a vms path */
1226 {
1227 *first_slash = ':';
1228 }
1229 else if ((first_slash[1] == '[') /* skip './' in './[dir' */
1230 && (first_slash[-1] == '.'))
1231 fullname += 2;
1232 }
1233
1234 /* Get part after first ':' (basename[-1] == ':')
1235 or last '/' (basename[-1] == '/'). */
1236
1237 basename = base_name (fullname);
1238
1239 local_ptr = Local; /* initialize */
1240
1241 /* We are trying to do a number of things here. First of all, we are
1242 trying to hammer the filenames into a standard format, such that later
1243 processing can handle them.
1244
1245 If the file name contains something like [dir.], then it recognizes this
1246 as a root, and strips the ".]". Later processing will add whatever is
1247 needed to get things working properly.
1248
1249 If no device is specified, then the first directory name is taken to be
1250 a device name (or a rooted logical). */
1251
1252 /* Point to the UNIX filename part (which needs to be fixed!)
1253 but skip vms path information.
1254 [basename != fullname since first_slash != 0]. */
1255
1256 if ((basename[-1] == ':') /* vms path spec. */
1257 || (basename[-1] == ']')
1258 || (basename[-1] == '>'))
1259 unixname = basename;
1260 else
1261 unixname = fullname;
1262
1263 if (*unixname == '/')
1264 unixname++;
1265
1266 /* If the directory spec is not rooted, we can just copy
1267 the UNIX filename part and we are done. */
1268
1269 if (((basename - fullname) > 1)
1270 && ( (basename[-1] == ']')
1271 || (basename[-1] == '>')))
1272 {
1273 if (basename[-2] != '.')
1274 {
1275
1276 /* The VMS part ends in a `]', and the preceding character is not a `.'.
1277 -> PATH]:/name (basename = '/name', unixname = 'name')
1278 We strip the `]', and then splice the two parts of the name in the
1279 usual way. Given the default locations for include files,
1280 we will only use this code if the user specifies alternate locations
1281 with the /include (-I) switch on the command line. */
1282
1283 basename -= 1; /* Strip "]" */
1284 unixname--; /* backspace */
1285 }
1286 else
1287 {
1288
1289 /* The VMS part has a ".]" at the end, and this will not do. Later
1290 processing will add a second directory spec, and this would be a syntax
1291 error. Thus we strip the ".]", and thus merge the directory specs.
1292 We also backspace unixname, so that it points to a '/'. This inhibits the
1293 generation of the 000000 root directory spec (which does not belong here
1294 in this case). */
1295
1296 basename -= 2; /* Strip ".]" */
1297 unixname--; /* backspace */
1298 }
1299 }
1300
1301 else
1302
1303 {
1304
1305 /* We drop in here if there is no VMS style directory specification yet.
1306 If there is no device specification either, we make the first dir a
1307 device and try that. If we do not do this, then we will be essentially
1308 searching the users default directory (as if they did a #include "asdf.h").
1309
1310 Then all we need to do is to push a '[' into the output string. Later
1311 processing will fill this in, and close the bracket. */
1312
1313 if ((unixname != fullname) /* vms path spec found. */
1314 && (basename[-1] != ':'))
1315 *local_ptr++ = ':'; /* dev not in spec. take first dir */
1316
1317 *local_ptr++ = '['; /* Open the directory specification */
1318 }
1319
1320 if (unixname == fullname) /* no vms dir spec. */
1321 {
1322 must_revert = 1;
1323 if ((first_slash != 0) /* unix dir spec. */
1324 && (*unixname != '/') /* not beginning with '/' */
1325 && (*unixname != '.')) /* or './' or '../' */
1326 *local_ptr++ = '.'; /* dir is local ! */
1327 }
1328
1329 /* at this point we assume that we have the device spec, and (at least
1330 the opening "[" for a directory specification. We may have directories
1331 specified already.
1332
1333 If there are no other slashes then the filename will be
1334 in the "root" directory. Otherwise, we need to add
1335 directory specifications. */
1336
1337 if (strchr (unixname, '/') == 0)
1338 {
1339 /* if no directories specified yet and none are following. */
1340 if (local_ptr[-1] == '[')
1341 {
1342 /* Just add "000000]" as the directory string */
1343 strcpy (local_ptr, "000000]");
1344 local_ptr += strlen (local_ptr);
1345 check_filename_before_returning = 1; /* we might need to fool with this later */
1346 }
1347 }
1348 else
1349 {
1350
1351 /* As long as there are still subdirectories to add, do them. */
1352 while (strchr (unixname, '/') != 0)
1353 {
1354 /* If this token is "." we can ignore it
1355 if it's not at the beginning of a path. */
1356 if ((unixname[0] == '.') && (unixname[1] == '/'))
1357 {
1358 /* remove it at beginning of path. */
1359 if ( ((unixname == fullname) /* no device spec */
1360 && (fullname+2 != basename)) /* starts with ./ */
1361 /* or */
1362 || ((basename[-1] == ':') /* device spec */
1363 && (unixname-1 == basename))) /* and ./ afterwards */
1364 *local_ptr++ = '.'; /* make '[.' start of path. */
1365 unixname += 2;
1366 continue;
1367 }
1368
1369 /* Add a subdirectory spec. Do not duplicate "." */
1370 if ( local_ptr[-1] != '.'
1371 && local_ptr[-1] != '['
1372 && local_ptr[-1] != '<')
1373 *local_ptr++ = '.';
1374
1375 /* If this is ".." then the spec becomes "-" */
1376 if ( (unixname[0] == '.')
1377 && (unixname[1] == '.')
1378 && (unixname[2] == '/'))
1379 {
1380 /* Add "-" and skip the ".." */
1381 if ((local_ptr[-1] == '.')
1382 && (local_ptr[-2] == '['))
1383 local_ptr--; /* prevent [.- */
1384 *local_ptr++ = '-';
1385 unixname += 3;
1386 continue;
1387 }
1388
1389 /* Copy the subdirectory */
1390 while (*unixname != '/')
1391 *local_ptr++= *unixname++;
1392
1393 unixname++; /* Skip the "/" */
1394 }
1395
1396 /* Close the directory specification */
1397 if (local_ptr[-1] == '.') /* no trailing periods */
1398 local_ptr--;
1399
1400 if (local_ptr[-1] == '[') /* no dir needed */
1401 local_ptr--;
1402 else
1403 *local_ptr++ = ']';
1404 }
1405
1406 /* Now add the filename. */
1407
1408 while (*unixname)
1409 *local_ptr++ = *unixname++;
1410 *local_ptr = 0;
1411
1412 /* Now append it to the original VMS spec. */
1413
1414 strcpy ((must_revert==1)?fullname:basename, Local);
1415
1416 /* If we put a [000000] in the filename, try to open it first. If this fails,
1417 remove the [000000], and return that name. This provides flexibility
1418 to the user in that they can use both rooted and non-rooted logical names
1419 to point to the location of the file. */
1420
1421 if (check_filename_before_returning)
1422 {
1423 f = open (fullname, O_RDONLY|O_NONBLOCK);
1424 if (f >= 0)
1425 {
1426 /* The file name is OK as it is, so return it as is. */
1427 close (f);
1428 return 1;
1429 }
1430
1431 /* The filename did not work. Try to remove the [000000] from the name,
1432 and return it. */
1433
1434 basename = strchr (fullname, '[');
1435 local_ptr = strchr (fullname, ']') + 1;
1436 strcpy (basename, local_ptr); /* this gets rid of it */
1437
1438 }
1439
1440 return 1;
1441 }
1442 #endif /* VMS */