OSDN Git Service

* rtl.h (insn_first_p): Declare.
[pf3gnuchains/gcc-fork.git] / gcc / cppfiles.c
1 /* Part of CPP library.  (include file handling)
2    Copyright (C) 1986, 87, 89, 92 - 95, 98, 1999 Free Software Foundation, Inc.
3    Written by Per Bothner, 1994.
4    Based on CCCP program by Paul Rubin, June 1986
5    Adapted to ANSI C, Richard Stallman, Jan 1987
6    Split out of cpplib.c, Zack Weinberg, Oct 1998
7
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
11 later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21
22  In other words, you are welcome to use, share and improve this program.
23  You are forbidden to forbid anyone else to use, share and improve
24  what you give them.   Help stamp out software-hoarding!  */
25
26 #include "config.h"
27 #include "system.h"
28 #include "cpplib.h"
29
30 /* The entry points to this file are: find_include_file, finclude,
31    include_hash, append_include_chain, deps_output, and file_cleanup.
32    file_cleanup is only called through CPP_BUFFER(pfile)->cleanup,
33    so it's static anyway. */
34
35 static struct include_hash *redundant_include_p
36                                         PROTO ((cpp_reader *,
37                                                 struct include_hash *,
38                                                 struct file_name_list *));
39 static struct file_name_map *read_name_map      PROTO ((cpp_reader *,
40                                                         const char *));
41 static char *read_filename_string       PROTO ((int, FILE *));
42 static char *remap_filename             PROTO ((cpp_reader *, char *,
43                                                 struct file_name_list *));
44 static long read_and_prescan            PROTO ((cpp_reader *, cpp_buffer *,
45                                                 int, size_t));
46 static void simplify_pathname           PROTO ((char *));
47 static struct file_name_list *actual_directory PROTO ((cpp_reader *, char *));
48
49 #if 0
50 static void hack_vms_include_specification PROTO ((char *));
51 #endif
52
53 /* Windows does not natively support inodes, and neither does MSDOS.
54    VMS has non-numeric inodes. */
55 #ifdef VMS
56 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
57 #elif (defined _WIN32 && !defined CYGWIN) || defined __MSDOS__
58 #define INO_T_EQ(a, b) 0
59 #else
60 #define INO_T_EQ(a, b) ((a) == (b))
61 #endif
62
63 /* Append an entry for dir DIR to list LIST, simplifying it if
64    possible.  SYS says whether this is a system include directory.
65    *** DIR is modified in place.  It must be writable and permanently
66    allocated. LIST is a pointer to the head pointer, because we actually
67    *prepend* the dir, and reverse the list later (in merge_include_chains). */
68 void
69 append_include_chain (pfile, list, dir, sysp)
70      cpp_reader *pfile;
71      struct file_name_list **list;
72      const char *dir;
73      int sysp;
74 {
75   struct file_name_list *new;
76   struct stat st;
77   unsigned int len;
78   char * newdir = xstrdup (dir);
79
80   simplify_pathname (newdir);
81   if (stat (newdir, &st))
82     {
83       /* Dirs that don't exist are silently ignored. */
84       if (errno != ENOENT)
85         cpp_perror_with_name (pfile, newdir);
86       return;
87     }
88
89   if (!S_ISDIR (st.st_mode))
90     {
91       cpp_message (pfile, 1, "%s: %s: Not a directory", progname, newdir);
92       return;
93     }
94
95   len = strlen(newdir);
96   if (len > pfile->max_include_len)
97     pfile->max_include_len = len;
98   
99   new = (struct file_name_list *)xmalloc (sizeof (struct file_name_list));
100   new->name = newdir;
101   new->nlen = len;
102   new->next = *list;
103   new->ino  = st.st_ino;
104   new->dev  = st.st_dev;
105   new->sysp = sysp;
106   new->name_map = NULL;
107
108   *list = new;
109 }
110
111 /* Merge the four include chains together in the order quote, bracket,
112    system, after.  Remove duplicate dirs (as determined by
113    INO_T_EQ()).  The system_include and after_include chains are never
114    referred to again after this function; all access is through the
115    bracket_include path.
116
117    For the future: Check if the directory is empty (but
118    how?) and possibly preload the include hash. */
119
120 void
121 merge_include_chains (opts)
122      struct cpp_options *opts;
123 {
124   struct file_name_list *prev, *next, *cur, *other;
125   struct file_name_list *quote, *brack, *systm, *after;
126   struct file_name_list *qtail, *btail, *stail, *atail;
127
128   qtail = opts->quote_include;
129   btail = opts->bracket_include;
130   stail = opts->system_include;
131   atail = opts->after_include;
132
133   /* Nreverse the four lists. */
134   prev = 0;
135   for (cur = qtail; cur; cur = next)
136     {
137       next = cur->next;
138       cur->next = prev;
139       prev = cur;
140     }
141   quote = prev;
142
143   prev = 0;
144   for (cur = btail; cur; cur = next)
145     {
146       next = cur->next;
147       cur->next = prev;
148       prev = cur;
149     }
150   brack = prev;
151
152   prev = 0;
153   for (cur = stail; cur; cur = next)
154     {
155       next = cur->next;
156       cur->next = prev;
157       prev = cur;
158     }
159   systm = prev;
160
161   prev = 0;
162   for (cur = atail; cur; cur = next)
163     {
164       next = cur->next;
165       cur->next = prev;
166       prev = cur;
167     }
168   after = prev;
169
170   /* Paste together bracket, system, and after include chains. */
171   if (stail)
172     stail->next = after;
173   else
174     systm = after;
175   if (btail)
176     btail->next = systm;
177   else
178     brack = systm;
179
180   /* This is a bit tricky.
181      First we drop dupes from the quote-include list.
182      Then we drop dupes from the bracket-include list.
183      Finally, if qtail and brack are the same directory,
184      we cut out qtail.
185
186      We can't just merge the lists and then uniquify them because
187      then we may lose directories from the <> search path that should
188      be there; consider -Ifoo -Ibar -I- -Ifoo -Iquux. It is however
189      safe to treat -Ibar -Ifoo -I- -Ifoo -Iquux as if written
190      -Ibar -I- -Ifoo -Iquux. */
191
192   for (cur = quote; cur; cur = cur->next)
193     {
194       for (other = quote; other != cur; other = other->next)
195         if (INO_T_EQ (cur->ino, other->ino)
196             && cur->dev == other->dev)
197           {
198             prev->next = cur->next;
199             free (cur->name);
200             free (cur);
201             cur = prev;
202             break;
203           }
204       prev = cur;
205     }
206   qtail = prev;
207
208   for (cur = brack; cur; cur = cur->next)
209     {
210       for (other = brack; other != cur; other = other->next)
211         if (INO_T_EQ (cur->ino, other->ino)
212             && cur->dev == other->dev)
213           {
214             prev->next = cur->next;
215             free (cur->name);
216             free (cur);
217             cur = prev;
218             break;
219           }
220       prev = cur;
221     }
222
223   if (quote)
224     {
225       if (INO_T_EQ (qtail->ino, brack->ino) && qtail->dev == brack->dev)
226         {
227           if (quote == qtail)
228             {
229               free (quote->name);
230               free (quote);
231               quote = brack;
232             }
233           else
234             {
235               cur = quote;
236               while (cur->next != qtail)
237                   cur = cur->next;
238               cur->next = brack;
239               free (qtail->name);
240               free (qtail);
241             }
242         }
243       else
244           qtail->next = brack;
245     }
246   else
247       quote = brack;
248
249   opts->quote_include = quote;
250   opts->bracket_include = brack;
251   opts->system_include = NULL;
252   opts->after_include = NULL;
253 }
254
255 /* Look up or add an entry to the table of all includes.  This table
256  is indexed by the name as it appears in the #include line.  The
257  ->next_this_file chain stores all different files with the same
258  #include name (there are at least three ways this can happen).  The
259  hash function could probably be improved a bit. */
260
261 struct include_hash *
262 include_hash (pfile, fname, add)
263      cpp_reader *pfile;
264      char *fname;
265      int add;
266 {
267   unsigned int hash = 0;
268   struct include_hash *l, *m;
269   char *f = fname;
270
271   while (*f)
272     hash += *f++;
273
274   l = pfile->all_include_files[hash % ALL_INCLUDE_HASHSIZE];
275   m = 0;
276   for (; l; m = l, l = l->next)
277     if (!strcmp (l->nshort, fname))
278       return l;
279
280   if (!add)
281     return 0;
282   
283   l = (struct include_hash *) xmalloc (sizeof (struct include_hash));
284   l->next = NULL;
285   l->next_this_file = NULL;
286   l->foundhere = NULL;
287   l->buf = NULL;
288   l->limit = NULL;
289   if (m)
290     m->next = l;
291   else
292     pfile->all_include_files[hash % ALL_INCLUDE_HASHSIZE] = l;
293   
294   return l;
295 }
296
297 /* Return 0 if the file pointed to by IHASH has never been included before,
298          -1 if it has been included before and need not be again,
299          or a pointer to an IHASH entry which is the file to be reread.
300    "Never before" is with respect to the position in ILIST.
301
302    This will not detect redundancies involving odd uses of the
303    `current directory' rule for "" includes.  They aren't quite
304    pathological, but I think they are rare enough not to worry about.
305    The simplest example is:
306
307    top.c:
308    #include "a/a.h"
309    #include "b/b.h"
310
311    a/a.h:
312    #include "../b/b.h"
313
314    and the problem is that for `current directory' includes,
315    ihash->foundhere is not on any of the global include chains,
316    so the test below (i->foundhere == l) may be false even when
317    the directories are in fact the same.  */
318
319 static struct include_hash *
320 redundant_include_p (pfile, ihash, ilist)
321      cpp_reader *pfile;
322      struct include_hash *ihash;
323      struct file_name_list *ilist;
324 {
325   struct file_name_list *l;
326   struct include_hash *i;
327
328   if (! ihash->foundhere)
329     return 0;
330
331   for (i = ihash; i; i = i->next_this_file)
332     for (l = ilist; l; l = l->next)
333        if (i->foundhere == l)
334          /* The control_macro works like this: If it's NULL, the file
335             is to be included again.  If it's "", the file is never to
336             be included again.  If it's a string, the file is not to be
337             included again if the string is the name of a defined macro. */
338          return (i->control_macro
339                  && (i->control_macro[0] == '\0'
340                      || cpp_lookup (pfile, i->control_macro, -1, -1)))
341              ? (struct include_hash *)-1 : i;
342
343   return 0;
344 }
345
346 static int
347 file_cleanup (pbuf, pfile)
348      cpp_buffer *pbuf;
349      cpp_reader *pfile;
350 {
351   if (pbuf->buf)
352     {
353       free (pbuf->buf);
354       pbuf->buf = 0;
355     }
356   if (pfile->system_include_depth)
357     pfile->system_include_depth--;
358   return 0;
359 }
360
361 /* Search for include file FNAME in the include chain starting at
362    SEARCH_START.  Return -2 if this file doesn't need to be included
363    (because it was included already and it's marked idempotent),
364    -1 if an error occurred, or a file descriptor open on the file.
365    *IHASH is set to point to the include hash entry for this file, and
366    *BEFORE is 1 if the file was included before (but needs to be read
367    again). */
368 int
369 find_include_file (pfile, fname, search_start, ihash, before)
370      cpp_reader *pfile;
371      char *fname;
372      struct file_name_list *search_start;
373      struct include_hash **ihash;
374      int *before;
375 {
376   struct file_name_list *l;
377   struct include_hash *ih, *jh;
378   int f, len;
379   char *name;
380   
381   ih = include_hash (pfile, fname, 1);
382   jh = redundant_include_p (pfile, ih,
383                             fname[0] == '/' ? ABSOLUTE_PATH : search_start);
384
385   if (jh != 0)
386     {
387       *before = 1;
388       *ihash = jh;
389
390       if (jh == (struct include_hash *)-1)
391         return -2;
392       else
393         return open (jh->name, O_RDONLY, 0666);
394     }
395
396   if (ih->foundhere)
397     /* A file is already known by this name, but it's not the same file.
398        Allocate another include_hash block and add it to the next_this_file
399        chain. */
400     {
401       jh = (struct include_hash *)xmalloc (sizeof (struct include_hash));
402       while (ih->next_this_file) ih = ih->next_this_file;
403
404       ih->next_this_file = jh;
405       jh = ih;
406       ih = ih->next_this_file;
407
408       ih->next = NULL;
409       ih->next_this_file = NULL;
410       ih->buf = NULL;
411       ih->limit = NULL;
412     }
413   *before = 0;
414   *ihash = ih;
415   ih->nshort = xstrdup (fname);
416   ih->control_macro = NULL;
417   
418   /* If the pathname is absolute, just open it. */ 
419   if (fname[0] == '/')
420     {
421       ih->foundhere = ABSOLUTE_PATH;
422       ih->name = ih->nshort;
423       return open (ih->name, O_RDONLY, 0666);
424     }
425
426   /* Search directory path, trying to open the file. */
427
428   len = strlen (fname);
429   name = xmalloc (len + pfile->max_include_len + 2 + INCLUDE_LEN_FUDGE);
430
431   for (l = search_start; l; l = l->next)
432     {
433       bcopy (l->name, name, l->nlen);
434       name[l->nlen] = '/';
435       strcpy (&name[l->nlen+1], fname);
436       simplify_pathname (name);
437       if (CPP_OPTIONS (pfile)->remap)
438         name = remap_filename (pfile, name, l);
439
440       f = open (name, O_RDONLY|O_NONBLOCK|O_NOCTTY, 0666);
441 #ifdef EACCES
442       if (f == -1 && errno == EACCES)
443         {
444           cpp_error(pfile, "included file `%s' exists but is not readable",
445                     name);
446           return -1;
447         }
448 #endif
449
450       if (f >= 0)
451         {
452           ih->foundhere = l;
453           ih->name = xrealloc (name, strlen (name)+1);
454           return f;
455         }
456     }
457   
458     if (jh)
459       {
460         jh->next_this_file = NULL;
461         free (ih);
462       }
463     free (name);
464     *ihash = (struct include_hash *)-1;
465     return -1;
466 }
467
468 /* The file_name_map structure holds a mapping of file names for a
469    particular directory.  This mapping is read from the file named
470    FILE_NAME_MAP_FILE in that directory.  Such a file can be used to
471    map filenames on a file system with severe filename restrictions,
472    such as DOS.  The format of the file name map file is just a series
473    of lines with two tokens on each line.  The first token is the name
474    to map, and the second token is the actual name to use.  */
475
476 struct file_name_map
477 {
478   struct file_name_map *map_next;
479   char *map_from;
480   char *map_to;
481 };
482
483 #define FILE_NAME_MAP_FILE "header.gcc"
484
485 /* Read a space delimited string of unlimited length from a stdio
486    file.  */
487
488 static char *
489 read_filename_string (ch, f)
490      int ch;
491      FILE *f;
492 {
493   char *alloc, *set;
494   int len;
495
496   len = 20;
497   set = alloc = xmalloc (len + 1);
498   if (! is_space[ch])
499     {
500       *set++ = ch;
501       while ((ch = getc (f)) != EOF && ! is_space[ch])
502         {
503           if (set - alloc == len)
504             {
505               len *= 2;
506               alloc = xrealloc (alloc, len + 1);
507               set = alloc + len / 2;
508             }
509           *set++ = ch;
510         }
511     }
512   *set = '\0';
513   ungetc (ch, f);
514   return alloc;
515 }
516
517 /* This structure holds a linked list of file name maps, one per directory.  */
518
519 struct file_name_map_list
520 {
521   struct file_name_map_list *map_list_next;
522   char *map_list_name;
523   struct file_name_map *map_list_map;
524 };
525
526 /* Read the file name map file for DIRNAME.  */
527
528 static struct file_name_map *
529 read_name_map (pfile, dirname)
530      cpp_reader *pfile;
531      const char *dirname;
532 {
533   register struct file_name_map_list *map_list_ptr;
534   char *name;
535   FILE *f;
536
537   for (map_list_ptr = CPP_OPTIONS (pfile)->map_list; map_list_ptr;
538        map_list_ptr = map_list_ptr->map_list_next)
539     if (! strcmp (map_list_ptr->map_list_name, dirname))
540       return map_list_ptr->map_list_map;
541
542   map_list_ptr = ((struct file_name_map_list *)
543                   xmalloc (sizeof (struct file_name_map_list)));
544   map_list_ptr->map_list_name = xstrdup (dirname);
545
546   name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
547   strcpy (name, dirname);
548   if (*dirname)
549     strcat (name, "/");
550   strcat (name, FILE_NAME_MAP_FILE);
551   f = fopen (name, "r");
552   if (!f)
553     map_list_ptr->map_list_map = (struct file_name_map *)-1;
554   else
555     {
556       int ch;
557       int dirlen = strlen (dirname);
558
559       while ((ch = getc (f)) != EOF)
560         {
561           char *from, *to;
562           struct file_name_map *ptr;
563
564           if (is_space[ch])
565             continue;
566           from = read_filename_string (ch, f);
567           while ((ch = getc (f)) != EOF && is_hor_space[ch])
568             ;
569           to = read_filename_string (ch, f);
570
571           ptr = ((struct file_name_map *)
572                  xmalloc (sizeof (struct file_name_map)));
573           ptr->map_from = from;
574
575           /* Make the real filename absolute.  */
576           if (*to == '/')
577             ptr->map_to = to;
578           else
579             {
580               ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
581               strcpy (ptr->map_to, dirname);
582               ptr->map_to[dirlen] = '/';
583               strcpy (ptr->map_to + dirlen + 1, to);
584               free (to);
585             }         
586
587           ptr->map_next = map_list_ptr->map_list_map;
588           map_list_ptr->map_list_map = ptr;
589
590           while ((ch = getc (f)) != '\n')
591             if (ch == EOF)
592               break;
593         }
594       fclose (f);
595     }
596   
597   map_list_ptr->map_list_next = CPP_OPTIONS (pfile)->map_list;
598   CPP_OPTIONS (pfile)->map_list = map_list_ptr;
599
600   return map_list_ptr->map_list_map;
601 }  
602
603 /* Remap NAME based on the file_name_map (if any) for LOC. */
604
605 static char *
606 remap_filename (pfile, name, loc)
607      cpp_reader *pfile;
608      char *name;
609      struct file_name_list *loc;
610 {
611   struct file_name_map *map;
612   const char *from, *p, *dir;
613
614   if (! loc->name_map)
615     loc->name_map = read_name_map (pfile,
616                                    loc->name
617                                    ? loc->name : ".");
618
619   if (loc->name_map == (struct file_name_map *)-1)
620     return name;
621   
622   from = name + strlen (loc->name) + 1;
623   
624   for (map = loc->name_map; map; map = map->map_next)
625     if (!strcmp (map->map_from, from))
626       return map->map_to;
627
628   /* Try to find a mapping file for the particular directory we are
629      looking in.  Thus #include <sys/types.h> will look up sys/types.h
630      in /usr/include/header.gcc and look up types.h in
631      /usr/include/sys/header.gcc.  */
632   p = rindex (name, '/');
633   if (!p)
634     p = name;
635   if (loc && loc->name
636       && strlen (loc->name) == (size_t) (p - name)
637       && !strncmp (loc->name, name, p - name))
638     /* FILENAME is in SEARCHPTR, which we've already checked.  */
639     return name;
640
641   if (p == name)
642     {
643       dir = ".";
644       from = name;
645     }
646   else
647     {
648       char * newdir = (char *) alloca (p - name + 1);
649       bcopy (name, newdir, p - name);
650       newdir[p - name] = '\0';
651       dir = newdir;
652       from = p + 1;
653     }
654   
655   for (map = read_name_map (pfile, dir); map; map = map->map_next)
656     if (! strcmp (map->map_from, name))
657       return map->map_to;
658
659   return name;
660 }
661
662 /* Read the contents of FD into the buffer on the top of PFILE's stack.
663    IHASH points to the include hash entry for the file associated with
664    FD.
665
666    The caller is responsible for the cpp_push_buffer.  */
667
668 int
669 finclude (pfile, fd, ihash)
670      cpp_reader *pfile;
671      int fd;
672      struct include_hash *ihash;
673 {
674   struct stat st;
675   size_t st_size;
676   long length;
677   cpp_buffer *fp;
678
679   if (fstat (fd, &st) < 0)
680     goto perror_fail;
681   if (fcntl (fd, F_SETFL, 0) == -1)  /* turn off nonblocking mode */
682     goto perror_fail;
683
684   fp = CPP_BUFFER (pfile);
685
686   if (S_ISREG (st.st_mode))
687     {
688       /* off_t might have a wider range than size_t - in other words,
689          the max size of a file might be bigger than the address
690          space, and we need to detect that now. */
691       st_size = (size_t) st.st_size;
692       if ((unsigned HOST_WIDE_INT) st_size
693           != (unsigned HOST_WIDE_INT) st.st_size)
694         {
695           cpp_error (pfile, "file `%s' is too large", ihash->name);
696           goto fail;
697         }
698     }
699   else if (S_ISFIFO (st.st_mode) || (S_ISCHR (st.st_mode) && isatty (fd)))
700     {
701       /* Cannot get its file size before reading.  4k is a decent
702          first guess. */
703       st_size = 4096;
704     }
705   else
706     {
707       cpp_error (pfile, "`%s' is not a file, pipe, or tty", ihash->name);
708       goto fail;
709     }
710
711   /* Read the file, converting end-of-line characters and trigraphs
712      (if enabled). */
713   fp->ihash = ihash;
714   fp->nominal_fname = fp->fname = ihash->name;
715   length = read_and_prescan (pfile, fp, fd, st_size);
716   if (length < 0)
717     goto fail;
718   if (length == 0)
719     ihash->control_macro = "";  /* never re-include */
720
721   close (fd);
722   fp->rlimit = fp->alimit = fp->buf + length;
723   fp->cur = fp->buf;
724   fp->system_header_p = (ihash->foundhere != ABSOLUTE_PATH
725                          && ihash->foundhere->sysp);
726   fp->lineno = 1;
727   fp->colno = 1;
728   fp->cleanup = file_cleanup;
729
730   /* The ->actual_dir field is only used when ignore_srcdir is not in effect;
731      see do_include */
732   if (!CPP_OPTIONS (pfile)->ignore_srcdir)
733     fp->actual_dir = actual_directory (pfile, fp->fname);
734
735   pfile->input_stack_listing_current = 0;
736   return 1;
737
738  perror_fail:
739   cpp_error_from_errno (pfile, ihash->name);
740  fail:
741   cpp_pop_buffer (pfile);
742   close (fd);
743   return 0;
744 }
745
746 static struct file_name_list *
747 actual_directory (pfile, fname)
748      cpp_reader *pfile;
749      char *fname;
750 {
751   char *last_slash, *dir;
752   size_t dlen;
753   struct file_name_list *x;
754   
755   dir = xstrdup (fname);
756   last_slash = rindex (dir, '/');
757   if (last_slash)
758     {
759       if (last_slash == dir)
760         {
761           dlen = 1;
762           last_slash[1] = '\0';
763         }
764       else
765         {
766           dlen = last_slash - dir;
767           *last_slash = '\0';
768         }
769     }
770   else
771     {
772       dir[0] = '.';
773       dir[1] = '\0';
774       dlen = 1;
775     }
776
777   if (dlen > pfile->max_include_len)
778     pfile->max_include_len = dlen;
779
780   for (x = pfile->actual_dirs; x; x = x->alloc)
781     if (!strcmp (x->name, dir))
782       {
783         free (dir);
784         return x;
785       }
786
787   /* Not found, make a new one. */
788   x = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
789   x->name = dir;
790   x->nlen = dlen;
791   x->next = CPP_OPTIONS (pfile)->quote_include;
792   x->alloc = pfile->actual_dirs;
793   x->sysp = 0;
794   x->name_map = NULL;
795
796   pfile->actual_dirs = x;
797   return x;
798 }
799
800 /* Read the entire contents of file DESC into buffer BUF, convert end-of-line
801    markers to canonical form, and convert trigraphs if enabled.  Also, make
802    sure there is a newline at the end of the file.  LEN is how much room we
803    have to start with (this can be expanded if necessary).
804    Returns -1 on failure, or the actual length of the data to be scanned.
805
806    N.B. This function has been rearranged to out-of-line the uncommon cases
807    as much as possible; this is important to prevent it from being a
808    performance bottleneck.  */
809
810 static long
811 read_and_prescan (pfile, fp, desc, len)
812      cpp_reader *pfile;
813      cpp_buffer *fp;
814      int desc;
815      size_t len;
816 {
817
818   U_CHAR *buf = (U_CHAR *) xmalloc (len);
819   U_CHAR *ip, *op, *line_base;
820   U_CHAR *ibase;
821   unsigned int line;
822   int count, seen_eof;
823   size_t offset;
824   /* 4096 bytes of buffer proper, 2 to detect running off the end without
825      address arithmetic all the time, and 2 for pushback in the case there's
826      a potential trigraph or end-of-line digraph at the end of a block. */
827 #define INTERMED_BUFFER_SIZE 4096
828   U_CHAR intermed[INTERMED_BUFFER_SIZE + 2 + 2];
829
830   offset = 0;
831   op = buf;
832   line_base = buf;
833   line = 1;
834   ibase = intermed + 2;
835   seen_eof = 0;
836
837   for (;;)
838     {
839     read_next:
840       count = read (desc, intermed + 2, INTERMED_BUFFER_SIZE);
841       if (count < 0)
842           goto error;
843       if (count == 0)
844         seen_eof = 1;
845       count += 2 - (ibase - intermed);
846       if (count == 0)
847         break;
848
849       ip = ibase;
850       ip[count] = ip[count+1] = '\0';
851       ibase = intermed + 2;
852       offset += count;
853
854       if (offset > len)
855         {
856           size_t delta_op = op - buf;
857           size_t delta_line_base = line_base - buf;
858           len *= 2;
859           if (offset > len)
860               /* len overflowed.
861                  This could happen if the file is larger than half the
862                  maximum address space of the machine. */
863             goto too_big;
864           buf = xrealloc (buf, len);
865           op = buf + delta_op;
866           line_base = buf + delta_line_base;
867         }
868
869       for (;;)
870         {
871           U_CHAR c;
872           c = *ip++;
873           switch (c)
874             {
875               /* The default case is at the top so gcc will realize
876                  it's the common case, and leave c in a register.
877                  Also, cache utilization is a little better this way. */
878             default:
879               *op++ = c;
880               break;
881               
882             case '\0':
883               if (seen_eof)
884                 goto eof;
885               else
886                 goto read_next;
887             case '\r':
888               if (*ip == '\n') ip++;
889               else if (*ip == '\0' && !seen_eof)
890                 {
891                   *--ibase = '\r';
892                   break;
893                 }
894               *op++ = '\n';
895               line++;
896               line_base = op;
897               break;
898
899             case '\n':
900               if (*ip == '\r') ip++;
901               else if (*ip == '\0' && !seen_eof)
902                 {
903                   *--ibase = '\n';
904                   break;
905                 }
906               *op++ = '\n';
907               line++;
908               line_base = op;
909               break;
910
911             case '?':
912               if (CPP_OPTIONS (pfile)->trigraphs
913                   || CPP_OPTIONS (pfile)->warn_trigraphs)
914                 {
915                   /* If we're at the end of the intermediate buffer,
916                      we have to shift the ?'s down to the start and
917                      come back next pass. */
918                   c = ip[0];
919                   if (c == '\0' && !seen_eof)
920                     {
921                       *--ibase = '?';
922                       break;
923                     }
924                   if (c != '?')
925                     {
926                       *op++ = '?';
927                       break;
928                     }
929                   c = ip[1];
930                   if (c == '\0' && !seen_eof)
931                     {
932                       *--ibase = '?';
933                       *--ibase = '?';
934                       break;
935                     }
936                   if (!trigraph_table[c])
937                     {
938                       *op++ = '?';
939                       break;
940                     }
941
942                   if (CPP_OPTIONS (pfile)->warn_trigraphs)
943                     cpp_warning_with_line (pfile, line, op-line_base,
944                                            "trigraph ??%c encountered", c);
945                   if (CPP_OPTIONS (pfile)->trigraphs)
946                     {
947                       *op++ = trigraph_table[c];
948                       ip += 2;
949                       break;
950                     }
951                   else
952                     {
953                       *op++ = '?';
954                       *op++ = '?';
955                       *op++ = c;
956                       ip += 2;
957                     }
958                 }
959               else
960                 *op++ = c;
961             }
962         }
963     }
964  eof:
965
966   if (op == buf)
967     return 0;
968
969   if (op[-1] != '\n' || op[-2] == '\\')
970     {
971       cpp_pedwarn_with_line (pfile, line, op - line_base,
972                              "no newline at end of file");
973       if (offset + 2 > len)
974         {
975           len += 2;
976           if (offset + 2 > len)
977             goto too_big;
978           buf = xrealloc (buf, len);
979           op = buf + offset;
980         }
981       if (op[-1] == '\\')
982         *op++ = '\n';
983       *op++ = '\n';
984     }
985
986   buf = xrealloc (buf, op - buf);
987   fp->buf = buf;
988   return op - buf;
989
990  too_big:
991   cpp_error (pfile, "file is too large");
992   free (buf);
993   return -1;
994
995  error:
996   cpp_error_from_errno (pfile, fp->fname);
997   free (buf);
998   return -1;
999 }
1000
1001 /* Add output to `deps_buffer' for the -M switch.
1002    STRING points to the text to be output.
1003    SPACER is ':' for targets, ' ' for dependencies, zero for text
1004    to be inserted literally.  */
1005
1006 void
1007 deps_output (pfile, string, spacer)
1008      cpp_reader *pfile;
1009      char *string;
1010      int spacer;
1011 {
1012   int size;
1013   int cr = 0;
1014
1015   if (!*string)
1016     return;
1017
1018   size = strlen (string);
1019
1020 #ifndef MAX_OUTPUT_COLUMNS
1021 #define MAX_OUTPUT_COLUMNS 72
1022 #endif
1023   if (pfile->deps_column > 0
1024       && (pfile->deps_column + size) > MAX_OUTPUT_COLUMNS)
1025     {
1026       size += 5;
1027       cr = 1;
1028       pfile->deps_column = 0;
1029     }
1030
1031   if (pfile->deps_size + size + 8 > pfile->deps_allocated_size)
1032     {
1033       pfile->deps_allocated_size = (pfile->deps_size + size + 50) * 2;
1034       pfile->deps_buffer = (char *) xrealloc (pfile->deps_buffer,
1035                                               pfile->deps_allocated_size);
1036     }
1037
1038   if (cr)
1039     {
1040       bcopy (" \\\n  ", &pfile->deps_buffer[pfile->deps_size], 5);
1041       pfile->deps_size += 5;
1042     }
1043   
1044   if (spacer == ' ' && pfile->deps_column > 0)
1045     pfile->deps_buffer[pfile->deps_size++] = ' ';
1046   bcopy (string, &pfile->deps_buffer[pfile->deps_size], size);
1047   pfile->deps_size += size;
1048   pfile->deps_column += size;
1049   if (spacer == ':')
1050     pfile->deps_buffer[pfile->deps_size++] = ':';
1051   pfile->deps_buffer[pfile->deps_size] = 0;
1052 }
1053
1054 /* Simplify a path name in place, deleting redundant components.  This
1055    reduces OS overhead and guarantees that equivalent paths compare
1056    the same (modulo symlinks).
1057
1058    Transforms made:
1059    foo/bar/../quux      foo/quux
1060    foo/./bar            foo/bar
1061    foo//bar             foo/bar
1062    /../quux             /quux
1063    //quux               //quux  (POSIX allows leading // as a namespace escape)
1064
1065    Guarantees no trailing slashes. All transforms reduce the length
1066    of the string.
1067  */
1068 static void
1069 simplify_pathname (path)
1070     char *path;
1071 {
1072     char *from, *to;
1073     char *base;
1074     int absolute = 0;
1075
1076 #if defined _WIN32 || defined __MSDOS__
1077     /* Convert all backslashes to slashes. */
1078     for (from = path; *from; from++)
1079         if (*from == '\\') *from = '/';
1080     
1081     /* Skip over leading drive letter if present. */
1082     if (ISALPHA (path[0]) && path[1] == ':')
1083         from = to = &path[2];
1084     else
1085         from = to = path;
1086 #else
1087     from = to = path;
1088 #endif
1089     
1090     /* Remove redundant initial /s.  */
1091     if (*from == '/')
1092     {
1093         absolute = 1;
1094         to++;
1095         from++;
1096         if (*from == '/')
1097         {
1098             if (*++from == '/')
1099                 /* 3 or more initial /s are equivalent to 1 /.  */
1100                 while (*++from == '/');
1101             else
1102                 /* On some hosts // differs from /; Posix allows this.  */
1103                 to++;
1104         }
1105     }
1106     base = to;
1107     
1108     for (;;)
1109     {
1110         while (*from == '/')
1111             from++;
1112
1113         if (from[0] == '.' && from[1] == '/')
1114             from += 2;
1115         else if (from[0] == '.' && from[1] == '\0')
1116             goto done;
1117         else if (from[0] == '.' && from[1] == '.' && from[2] == '/')
1118         {
1119             if (base == to)
1120             {
1121                 if (absolute)
1122                     from += 3;
1123                 else
1124                 {
1125                     *to++ = *from++;
1126                     *to++ = *from++;
1127                     *to++ = *from++;
1128                     base = to;
1129                 }
1130             }
1131             else
1132             {
1133                 to -= 2;
1134                 while (to > base && *to != '/') to--;
1135                 if (*to == '/')
1136                     to++;
1137                 from += 3;
1138             }
1139         }
1140         else if (from[0] == '.' && from[1] == '.' && from[2] == '\0')
1141         {
1142             if (base == to)
1143             {
1144                 if (!absolute)
1145                 {
1146                     *to++ = *from++;
1147                     *to++ = *from++;
1148                 }
1149             }
1150             else
1151             {
1152                 to -= 2;
1153                 while (to > base && *to != '/') to--;
1154                 if (*to == '/')
1155                     to++;
1156             }
1157             goto done;
1158         }
1159         else
1160             /* Copy this component and trailing /, if any.  */
1161             while ((*to++ = *from++) != '/')
1162             {
1163                 if (!to[-1])
1164                 {
1165                     to--;
1166                     goto done;
1167                 }
1168             }
1169         
1170     }
1171     
1172  done:
1173     /* Trim trailing slash */
1174     if (to[0] == '/' && (!absolute || to > path+1))
1175         to--;
1176
1177     /* Change the empty string to "." so that stat() on the result
1178        will always work. */
1179     if (to == path)
1180       *to++ = '.';
1181     
1182     *to = '\0';
1183
1184     return;
1185 }
1186
1187 /* It is not clear when this should be used if at all, so I've
1188    disabled it until someone who understands VMS can look at it. */
1189 #if 0
1190
1191 /* Under VMS we need to fix up the "include" specification filename.
1192
1193    Rules for possible conversions
1194
1195         fullname                tried paths
1196
1197         name                    name
1198         ./dir/name              [.dir]name
1199         /dir/name               dir:name
1200         /name                   [000000]name, name
1201         dir/name                dir:[000000]name, dir:name, dir/name
1202         dir1/dir2/name          dir1:[dir2]name, dir1:[000000.dir2]name
1203         path:/name              path:[000000]name, path:name
1204         path:/dir/name          path:[000000.dir]name, path:[dir]name
1205         path:dir/name           path:[dir]name
1206         [path]:[dir]name        [path.dir]name
1207         path/[dir]name          [path.dir]name
1208
1209    The path:/name input is constructed when expanding <> includes. */
1210
1211
1212 static void
1213 hack_vms_include_specification (fullname)
1214      char *fullname;
1215 {
1216   register char *basename, *unixname, *local_ptr, *first_slash;
1217   int f, check_filename_before_returning, must_revert;
1218   char Local[512];
1219
1220   check_filename_before_returning = 0;
1221   must_revert = 0;
1222   /* See if we can find a 1st slash. If not, there's no path information.  */
1223   first_slash = index (fullname, '/');
1224   if (first_slash == 0)
1225     return 0;                           /* Nothing to do!!! */
1226
1227   /* construct device spec if none given.  */
1228
1229   if (index (fullname, ':') == 0)
1230     {
1231
1232       /* If fullname has a slash, take it as device spec.  */
1233
1234       if (first_slash == fullname)
1235         {
1236           first_slash = index (fullname+1, '/');        /* 2nd slash ? */
1237           if (first_slash)
1238             *first_slash = ':';                         /* make device spec  */
1239           for (basename = fullname; *basename != 0; basename++)
1240             *basename = *(basename+1);                  /* remove leading slash  */
1241         }
1242       else if ((first_slash[-1] != '.')         /* keep ':/', './' */
1243             && (first_slash[-1] != ':')
1244             && (first_slash[-1] != ']'))        /* or a vms path  */
1245         {
1246           *first_slash = ':';
1247         }
1248       else if ((first_slash[1] == '[')          /* skip './' in './[dir'  */
1249             && (first_slash[-1] == '.'))
1250         fullname += 2;
1251     }
1252
1253   /* Get part after first ':' (basename[-1] == ':')
1254      or last '/' (basename[-1] == '/').  */
1255
1256   basename = base_name (fullname);
1257
1258   local_ptr = Local;                    /* initialize */
1259
1260   /* We are trying to do a number of things here.  First of all, we are
1261      trying to hammer the filenames into a standard format, such that later
1262      processing can handle them.
1263      
1264      If the file name contains something like [dir.], then it recognizes this
1265      as a root, and strips the ".]".  Later processing will add whatever is
1266      needed to get things working properly.
1267      
1268      If no device is specified, then the first directory name is taken to be
1269      a device name (or a rooted logical).  */
1270
1271   /* Point to the UNIX filename part (which needs to be fixed!)
1272      but skip vms path information.
1273      [basename != fullname since first_slash != 0].  */
1274
1275   if ((basename[-1] == ':')             /* vms path spec.  */
1276       || (basename[-1] == ']')
1277       || (basename[-1] == '>'))
1278     unixname = basename;
1279   else
1280     unixname = fullname;
1281
1282   if (*unixname == '/')
1283     unixname++;
1284
1285   /* If the directory spec is not rooted, we can just copy
1286      the UNIX filename part and we are done.  */
1287
1288   if (((basename - fullname) > 1)
1289      && (  (basename[-1] == ']')
1290         || (basename[-1] == '>')))
1291     {
1292       if (basename[-2] != '.')
1293         {
1294
1295         /* The VMS part ends in a `]', and the preceding character is not a `.'.
1296            -> PATH]:/name (basename = '/name', unixname = 'name')
1297            We strip the `]', and then splice the two parts of the name in the
1298            usual way.  Given the default locations for include files in cccp.c,
1299            we will only use this code if the user specifies alternate locations
1300            with the /include (-I) switch on the command line.  */
1301
1302           basename -= 1;        /* Strip "]" */
1303           unixname--;           /* backspace */
1304         }
1305       else
1306         {
1307
1308         /* The VMS part has a ".]" at the end, and this will not do.  Later
1309            processing will add a second directory spec, and this would be a syntax
1310            error.  Thus we strip the ".]", and thus merge the directory specs.
1311            We also backspace unixname, so that it points to a '/'.  This inhibits the
1312            generation of the 000000 root directory spec (which does not belong here
1313            in this case).  */
1314
1315           basename -= 2;        /* Strip ".]" */
1316           unixname--;           /* backspace */
1317         }
1318     }
1319
1320   else
1321
1322     {
1323
1324       /* We drop in here if there is no VMS style directory specification yet.
1325          If there is no device specification either, we make the first dir a
1326          device and try that.  If we do not do this, then we will be essentially
1327          searching the users default directory (as if they did a #include "asdf.h").
1328         
1329          Then all we need to do is to push a '[' into the output string. Later
1330          processing will fill this in, and close the bracket.  */
1331
1332       if ((unixname != fullname)        /* vms path spec found.  */
1333          && (basename[-1] != ':'))
1334         *local_ptr++ = ':';             /* dev not in spec.  take first dir */
1335
1336       *local_ptr++ = '[';               /* Open the directory specification */
1337     }
1338
1339     if (unixname == fullname)           /* no vms dir spec.  */
1340       {
1341         must_revert = 1;
1342         if ((first_slash != 0)          /* unix dir spec.  */
1343             && (*unixname != '/')       /* not beginning with '/'  */
1344             && (*unixname != '.'))      /* or './' or '../'  */
1345           *local_ptr++ = '.';           /* dir is local !  */
1346       }
1347
1348   /* at this point we assume that we have the device spec, and (at least
1349      the opening "[" for a directory specification.  We may have directories
1350      specified already.
1351
1352      If there are no other slashes then the filename will be
1353      in the "root" directory.  Otherwise, we need to add
1354      directory specifications.  */
1355
1356   if (index (unixname, '/') == 0)
1357     {
1358       /* if no directories specified yet and none are following.  */
1359       if (local_ptr[-1] == '[')
1360         {
1361           /* Just add "000000]" as the directory string */
1362           strcpy (local_ptr, "000000]");
1363           local_ptr += strlen (local_ptr);
1364           check_filename_before_returning = 1; /* we might need to fool with this later */
1365         }
1366     }
1367   else
1368     {
1369
1370       /* As long as there are still subdirectories to add, do them.  */
1371       while (index (unixname, '/') != 0)
1372         {
1373           /* If this token is "." we can ignore it
1374                if it's not at the beginning of a path.  */
1375           if ((unixname[0] == '.') && (unixname[1] == '/'))
1376             {
1377               /* remove it at beginning of path.  */
1378               if (  ((unixname == fullname)             /* no device spec  */
1379                     && (fullname+2 != basename))        /* starts with ./ */
1380                                                         /* or  */
1381                  || ((basename[-1] == ':')              /* device spec  */
1382                     && (unixname-1 == basename)))       /* and ./ afterwards  */
1383                 *local_ptr++ = '.';                     /* make '[.' start of path.  */
1384               unixname += 2;
1385               continue;
1386             }
1387
1388           /* Add a subdirectory spec. Do not duplicate "." */
1389           if (  local_ptr[-1] != '.'
1390              && local_ptr[-1] != '['
1391              && local_ptr[-1] != '<')
1392             *local_ptr++ = '.';
1393
1394           /* If this is ".." then the spec becomes "-" */
1395           if (  (unixname[0] == '.')
1396              && (unixname[1] == '.')
1397              && (unixname[2] == '/'))
1398             {
1399               /* Add "-" and skip the ".." */
1400               if ((local_ptr[-1] == '.')
1401                   && (local_ptr[-2] == '['))
1402                 local_ptr--;                    /* prevent [.-  */
1403               *local_ptr++ = '-';
1404               unixname += 3;
1405               continue;
1406             }
1407
1408           /* Copy the subdirectory */
1409           while (*unixname != '/')
1410             *local_ptr++= *unixname++;
1411
1412           unixname++;                   /* Skip the "/" */
1413         }
1414
1415       /* Close the directory specification */
1416       if (local_ptr[-1] == '.')         /* no trailing periods */
1417         local_ptr--;
1418
1419       if (local_ptr[-1] == '[')         /* no dir needed */
1420         local_ptr--;
1421       else
1422         *local_ptr++ = ']';
1423     }
1424
1425   /* Now add the filename.  */
1426
1427   while (*unixname)
1428     *local_ptr++ = *unixname++;
1429   *local_ptr = 0;
1430
1431   /* Now append it to the original VMS spec.  */
1432
1433   strcpy ((must_revert==1)?fullname:basename, Local);
1434
1435   /* If we put a [000000] in the filename, try to open it first. If this fails,
1436      remove the [000000], and return that name.  This provides flexibility
1437      to the user in that they can use both rooted and non-rooted logical names
1438      to point to the location of the file.  */
1439
1440   if (check_filename_before_returning)
1441     {
1442       f = open (fullname, O_RDONLY, 0666);
1443       if (f >= 0)
1444         {
1445           /* The file name is OK as it is, so return it as is.  */
1446           close (f);
1447           return 1;
1448         }
1449
1450       /* The filename did not work.  Try to remove the [000000] from the name,
1451          and return it.  */
1452
1453       basename = index (fullname, '[');
1454       local_ptr = index (fullname, ']') + 1;
1455       strcpy (basename, local_ptr);             /* this gets rid of it */
1456
1457     }
1458
1459   return 1;
1460 }
1461 #endif  /* VMS */