OSDN Git Service

alphabatize irix___restrict
[pf3gnuchains/gcc-fork.git] / gcc / c-incpath.c
1 /* Set up combined include path chain for the preprocessor.
2    Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
4
5    Broken out of cppinit.c and cppfiles.c and rewritten Mar 2003.
6
7 This program is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 2, or (at your option) any
10 later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "cpplib.h"
26 #include "prefix.h"
27 #include "intl.h"
28 #include "c-incpath.h"
29 #include "cppdefault.h"
30
31 /* Windows does not natively support inodes, and neither does MSDOS.
32    Cygwin's emulation can generate non-unique inodes, so don't use it.
33    VMS has non-numeric inodes.  */
34 #ifdef VMS
35 # define INO_T_EQ(A, B) (!memcmp (&(A), &(B), sizeof (A)))
36 # define INO_T_COPY(DEST, SRC) memcpy(&(DEST), &(SRC), sizeof (SRC))
37 #else
38 # if (defined _WIN32 && ! defined (_UWIN)) || defined __MSDOS__
39 #  define INO_T_EQ(A, B) 0
40 # else
41 #  define INO_T_EQ(A, B) ((A) == (B))
42 # endif
43 # define INO_T_COPY(DEST, SRC) (DEST) = (SRC)
44 #endif
45
46 static void add_env_var_paths PARAMS ((const char *, int));
47 static void add_standard_paths PARAMS ((const char *, const char *, int));
48 static void free_path PARAMS ((struct cpp_path *, int));
49 static void merge_include_chains PARAMS ((cpp_reader *, int));
50 static int remove_component_p PARAMS ((const char *));
51 static struct cpp_path *
52   remove_duplicates PARAMS ((cpp_reader *, struct cpp_path *,
53                              struct cpp_path *, struct cpp_path *, int));
54
55 /* Include chains heads and tails.  */
56 static struct cpp_path *heads[4];
57 static struct cpp_path *tails[4];
58 static bool quote_ignores_source_dir;
59 enum { REASON_QUIET = 0, REASON_NOENT, REASON_DUP, REASON_DUP_SYS };
60
61 /* Free an element of the include chain, possibly giving a reason.  */
62 static void
63 free_path (path, reason)
64      struct cpp_path *path;
65      int reason;
66 {
67   switch (reason)
68     {
69     case REASON_DUP:
70     case REASON_DUP_SYS:
71       fprintf (stderr, _("ignoring duplicate directory \"%s\"\n"), path->name);
72       if (reason == REASON_DUP_SYS)
73         fprintf (stderr,
74  _("  as it is a non-system directory that duplicates a system directory\n"));
75       break;
76
77     case REASON_NOENT:
78       fprintf (stderr, _("ignoring nonexistent directory \"%s\"\n"),
79                path->name);
80       break;
81
82     case REASON_QUIET:
83     default:
84       break;
85     }
86
87   free ((PTR) path->name);
88   free (path);
89 }
90
91 /* Read ENV_VAR for a PATH_SEPARATOR-separated list of file names; and
92    append all the names to the search path CHAIN.  */
93 static void
94 add_env_var_paths (env_var, chain)
95      const char *env_var;
96      int chain;
97 {
98   char *p, *q, *path;
99
100   GET_ENVIRONMENT (q, env_var);
101
102   if (!q)
103     return;
104
105   for (p = q; *q; p = q + 1)
106     {
107       q = p;
108       while (*q != 0 && *q != PATH_SEPARATOR)
109         q++;
110
111       if (p == q)
112         path = xstrdup (".");
113       else
114         {
115           path = xmalloc (q - p + 1);
116           memcpy (path, p, q - p);
117           path[q - p] = '\0';
118         }
119
120       add_path (path, chain, chain == SYSTEM);
121     }
122 }
123
124 /* Append the standard include chain defined in cppdefault.c.  */
125 static void
126 add_standard_paths (sysroot, iprefix, cxx_stdinc)
127      const char *sysroot, *iprefix;
128      int cxx_stdinc;
129 {
130   const struct default_include *p;
131   size_t len = 0;
132
133   if (iprefix)
134     len = cpp_GCC_INCLUDE_DIR_len;
135
136   for (p = cpp_include_defaults; p->fname; p++)
137     {
138       if (!p->cplusplus || cxx_stdinc)
139         {
140           char *str;
141
142           /* Should this directory start with the sysroot?  */
143           if (sysroot && p->add_sysroot)
144             str = concat (sysroot, p->fname, NULL);
145           /* Does this directory start with the prefix?  If so, search
146              "translated" versions of GNU directories.  These have
147              /usr/local/lib/gcc... replaced by iprefix.  */
148           else if (len && !strncmp (p->fname, cpp_GCC_INCLUDE_DIR, len))
149             str = concat (iprefix, p->fname + len, NULL);
150           else
151             str = update_path (p->fname, p->component);
152
153           add_path (str, SYSTEM, p->cxx_aware);
154         }
155     }
156 }
157
158 /* For each duplicate path in chain HEAD, keep just the first one.
159    Remove each path in chain HEAD that also exists in chain SYSTEM.
160    Set the NEXT pointer of the last path in the resulting chain to
161    JOIN, unless it duplicates JOIN in which case the last path is
162    removed.  Return the head of the resulting chain.  Any of HEAD,
163    JOIN and SYSTEM can be NULL.  */
164 static struct cpp_path *
165 remove_duplicates (pfile, head, system, join, verbose)
166      cpp_reader *pfile;
167      struct cpp_path *head;
168      struct cpp_path *system;
169      struct cpp_path *join;
170      int verbose;
171 {
172   struct cpp_path **pcur, *tmp, *cur;
173   struct stat st;
174
175   for (pcur = &head; *pcur; )
176     {
177       int reason = REASON_QUIET;
178
179       cur = *pcur;
180       simplify_path (cur->name);
181
182       if (stat (cur->name, &st))
183         {
184           /* Dirs that don't exist are silently ignored, unless verbose.  */
185           if (errno != ENOENT)
186             cpp_errno (pfile, DL_ERROR, cur->name);
187           else
188             reason = REASON_NOENT;
189         }
190       else if (!S_ISDIR (st.st_mode))
191         cpp_error_with_line (pfile, DL_ERROR, 0, 0,
192                              "%s: not a directory", cur->name);
193       else
194         {
195           INO_T_COPY (cur->ino, st.st_ino);
196           cur->dev  = st.st_dev;
197
198           /* Remove this one if it is in the system chain.  */
199           reason = REASON_DUP_SYS;
200           for (tmp = system; tmp; tmp = tmp->next)
201             if (INO_T_EQ (tmp->ino, cur->ino) && tmp->dev == cur->dev)
202               break;
203
204           if (!tmp)
205             {
206               /* Dupicate of something earlier in the same chain?  */
207               reason = REASON_DUP;
208               for (tmp = head; tmp != cur; tmp = tmp->next)
209                 if (INO_T_EQ (cur->ino, tmp->ino) && cur->dev == tmp->dev)
210                   break;
211
212               if (tmp == cur
213                   /* Last in the chain and duplicate of JOIN?  */
214                   && !(cur->next == NULL && join
215                        && INO_T_EQ (cur->ino, join->ino)
216                        && cur->dev == join->dev))
217                 {
218                   /* Unique, so keep this directory.  */
219                   pcur = &cur->next;
220                   continue;
221                 }
222             }
223         }
224
225       /* Remove this entry from the chain.  */
226       *pcur = cur->next;
227       free_path (cur, verbose ? reason: REASON_QUIET);
228     }
229
230   *pcur = join;
231   return head;
232 }
233
234 /* Merge the four include chains together in the order quote, bracket,
235    system, after.  Remove duplicate dirs (as determined by
236    INO_T_EQ()).
237
238    We can't just merge the lists and then uniquify them because then
239    we may lose directories from the <> search path that should be
240    there; consider -Ifoo -Ibar -I- -Ifoo -Iquux.  It is however safe
241    to treat -Ibar -Ifoo -I- -Ifoo -Iquux as if written -Ibar -I- -Ifoo
242    -Iquux.  */
243 static void
244 merge_include_chains (pfile, verbose)
245      cpp_reader *pfile;
246      int verbose;
247 {
248   /* Join the SYSTEM and AFTER chains.  Remove duplicates in the
249      resulting SYSTEM chain.  */
250   if (heads[SYSTEM])
251     tails[SYSTEM]->next = heads[AFTER];
252   else
253     heads[SYSTEM] = heads[AFTER];
254   heads[SYSTEM] = remove_duplicates (pfile, heads[SYSTEM], 0, 0, verbose);
255
256   /* Remove duplicates from BRACKET that are in itself or SYSTEM, and
257      join it to SYSTEM.  */
258   heads[BRACKET] = remove_duplicates (pfile, heads[BRACKET], heads[SYSTEM],
259                                       heads[SYSTEM], verbose);
260
261   /* Remove duplicates from QUOTE that are in itself or SYSTEM, and
262      join it to BRACKET.  */
263   heads[QUOTE] = remove_duplicates (pfile, heads[QUOTE], heads[SYSTEM],
264                                     heads[BRACKET], verbose);
265
266   /* If verbose, print the list of dirs to search.  */
267   if (verbose)
268     {
269       struct cpp_path *p;
270
271       fprintf (stderr, _("#include \"...\" search starts here:\n"));
272       for (p = heads[QUOTE];; p = p->next)
273         {
274           if (p == heads[BRACKET])
275             fprintf (stderr, _("#include <...> search starts here:\n"));
276           if (!p)
277             break;
278           fprintf (stderr, " %s\n", p->name);
279         }
280       fprintf (stderr, _("End of search list.\n"));
281     }
282 }
283
284 /* Use given -I paths for #include "..." but not #include <...>, and
285    don't search the directory of the present file for #include "...".
286    (Note that -I. -I- is not the same as the default setup; -I. uses
287    the compiler's working dir.)  */
288 void
289 split_quote_chain ()
290 {
291   heads[QUOTE] = heads[BRACKET];
292   tails[QUOTE] = tails[BRACKET];
293   heads[BRACKET] = NULL;
294   tails[BRACKET] = NULL;
295   /* This is NOT redundant.  */
296   quote_ignores_source_dir = true;
297 }
298
299 /* Add PATH to the include chain CHAIN. PATH must be malloc-ed and
300    NUL-terminated.  */
301 void
302 add_path (path, chain, cxx_aware)
303      char *path;
304      int chain;
305      int cxx_aware;
306 {
307   struct cpp_path *p;
308
309   p = (struct cpp_path *) xmalloc (sizeof (struct cpp_path));
310   p->next = NULL;
311   p->name = path;
312   if (chain == SYSTEM || chain == AFTER)
313     p->sysp = 1 + (cxx_aware != 0);
314   else
315     p->sysp = 0;
316
317   if (tails[chain])
318     tails[chain]->next = p;
319   else
320     heads[chain] = p;
321   tails[chain] = p;
322 }
323
324 /* Exported function to handle include chain merging, duplicate
325    removal, and registration with cpplib.  */
326 void
327 register_include_chains (pfile, sysroot, iprefix,
328                          stdinc, cxx_stdinc, verbose)
329      cpp_reader *pfile;
330      const char *sysroot, *iprefix;
331      int stdinc, cxx_stdinc, verbose;
332 {
333   static const char *const lang_env_vars[] =
334     { "C_INCLUDE_PATH", "CPLUS_INCLUDE_PATH",
335       "OBJC_INCLUDE_PATH", "OBJCPLUS_INCLUDE_PATH" };
336   cpp_options *cpp_opts = cpp_get_options (pfile);
337   size_t idx = (cpp_opts->objc ? 2: 0);
338
339   if (cpp_opts->cplusplus)
340     idx++;
341   else
342     cxx_stdinc = false;
343
344   /* CPATH and language-dependent environment variables may add to the
345      include chain.  */
346   add_env_var_paths ("CPATH", BRACKET);
347   add_env_var_paths (lang_env_vars[idx], SYSTEM);
348
349   /* Finally chain on the standard directories.  */
350   if (stdinc)
351     add_standard_paths (sysroot, iprefix, cxx_stdinc);
352
353   merge_include_chains (pfile, verbose);
354
355   cpp_set_include_chains (pfile, heads[QUOTE], heads[BRACKET],
356                           quote_ignores_source_dir);
357 }
358
359 /* Returns true if it is safe to remove the final component of path,
360    when it is followed by a ".." component.  We use lstat to avoid
361    symlinks if we have it.  If not, we can still catch errors with
362    stat ().  */
363 static int
364 remove_component_p (path)
365      const char *path;
366 {
367   struct stat s;
368   int result;
369
370 #ifdef HAVE_LSTAT
371   result = lstat (path, &s);
372 #else
373   result = stat (path, &s);
374 #endif
375
376   /* There's no guarantee that errno will be unchanged, even on
377      success.  Cygwin's lstat(), for example, will often set errno to
378      ENOSYS.  In case of success, reset errno to zero.  */
379   if (result == 0)
380     errno = 0;
381
382   return result == 0 && S_ISDIR (s.st_mode);
383 }
384
385 /* Simplify a path name in place, deleting redundant components.  This
386    reduces OS overhead and guarantees that equivalent paths compare
387    the same (modulo symlinks).
388
389    Transforms made:
390    foo/bar/../quux      foo/quux
391    foo/./bar            foo/bar
392    foo//bar             foo/bar
393    /../quux             /quux
394    //quux               //quux  (POSIX allows leading // as a namespace escape)
395
396    Guarantees no trailing slashes.  All transforms reduce the length
397    of the string.  Returns PATH.  errno is 0 if no error occurred;
398    nonzero if an error occurred when using stat () or lstat ().  */
399 void
400 simplify_path (path)
401      char *path ATTRIBUTE_UNUSED;
402 {
403 #ifndef VMS
404   char *from, *to;
405   char *base, *orig_base;
406   int absolute = 0;
407
408   errno = 0;
409   /* Don't overflow the empty path by putting a '.' in it below.  */
410   if (*path == '\0')
411     return;
412
413 #if defined (HAVE_DOS_BASED_FILE_SYSTEM)
414   /* Convert all backslashes to slashes.  */
415   for (from = path; *from; from++)
416     if (*from == '\\') *from = '/';
417
418   /* Skip over leading drive letter if present.  */
419   if (ISALPHA (path[0]) && path[1] == ':')
420     from = to = &path[2];
421   else
422     from = to = path;
423 #else
424   from = to = path;
425 #endif
426
427   /* Remove redundant leading /s.  */
428   if (*from == '/')
429     {
430       absolute = 1;
431       to++;
432       from++;
433       if (*from == '/')
434         {
435           if (*++from == '/')
436             /* 3 or more initial /s are equivalent to 1 /.  */
437             while (*++from == '/');
438           else
439             /* On some hosts // differs from /; Posix allows this.  */
440             to++;
441         }
442     }
443
444   base = orig_base = to;
445   for (;;)
446     {
447       int move_base = 0;
448
449       while (*from == '/')
450         from++;
451
452       if (*from == '\0')
453         break;
454
455       if (*from == '.')
456         {
457           if (from[1] == '\0')
458             break;
459           if (from[1] == '/')
460             {
461               from += 2;
462               continue;
463             }
464           else if (from[1] == '.' && (from[2] == '/' || from[2] == '\0'))
465             {
466               /* Don't simplify if there was no previous component.  */
467               if (absolute && orig_base == to)
468                 {
469                   from += 2;
470                   continue;
471                 }
472               /* Don't simplify if the previous component was "../",
473                  or if an error has already occurred with (l)stat.  */
474               if (base != to && errno == 0)
475                 {
476                   /* We don't back up if it's a symlink.  */
477                   *to = '\0';
478                   if (remove_component_p (path))
479                     {
480                       while (to > base && *to != '/')
481                         to--;
482                       from += 2;
483                       continue;
484                     }
485                 }
486               move_base = 1;
487             }
488         }
489
490       /* Add the component separator.  */
491       if (to > orig_base)
492         *to++ = '/';
493
494       /* Copy this component until the trailing null or '/'.  */
495       while (*from != '\0' && *from != '/')
496         *to++ = *from++;
497
498       if (move_base)
499         base = to;
500     }
501
502   /* Change the empty string to "." so that it is not treated as stdin.
503      Null terminate.  */
504   if (to == path)
505     *to++ = '.';
506   *to = '\0';
507 #else  /* VMS */
508   errno = 0;
509 #endif /* !VMS  */
510 }