OSDN Git Service

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