1/* Set up combined include path chain for the preprocessor.
2   Copyright (C) 1986-2015 Free Software Foundation, Inc.
3
4   Broken out of cppinit.c and cppfiles.c and rewritten Mar 2003.
5
6   This program is free software; you can redistribute it and/or modify it
7   under the terms of the GNU General Public License as published by the
8   Free Software Foundation; either version 3, or (at your option) any
9   later version.
10
11   This program is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program; see the file COPYING3.  If not see
18   <http://www.gnu.org/licenses/>.  */
19
20#include "config.h"
21#include "system.h"
22#include "coretypes.h"
23#include "machmode.h"
24#include "target.h"
25#include "tm.h"
26#include "cpplib.h"
27#include "prefix.h"
28#include "intl.h"
29#include "incpath.h"
30#include "cppdefault.h"
31
32/* Microsoft Windows does not natively support inodes.
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#elif !defined (HOST_LACKS_INODE_NUMBERS)
38# define INO_T_EQ(A, B) ((A) == (B))
39# define INO_T_COPY(DEST, SRC) (DEST) = (SRC)
40#endif
41
42#if defined INO_T_EQ
43#define DIRS_EQ(A, B) ((A)->dev == (B)->dev \
44	&& INO_T_EQ ((A)->ino, (B)->ino))
45#else
46#define DIRS_EQ(A, B) (!filename_cmp ((A)->canonical_name, (B)->canonical_name))
47#endif
48
49static const char dir_separator_str[] = { DIR_SEPARATOR, 0 };
50
51static void add_env_var_paths (const char *, int);
52static void add_standard_paths (const char *, const char *, const char *, int);
53static void free_path (struct cpp_dir *, int);
54static void merge_include_chains (const char *, cpp_reader *, int);
55static void add_sysroot_to_chain (const char *, int);
56static struct cpp_dir *remove_duplicates (cpp_reader *, struct cpp_dir *,
57					   struct cpp_dir *,
58					   struct cpp_dir *, int);
59
60/* Include chains heads and tails.  */
61static struct cpp_dir *heads[4];
62static struct cpp_dir *tails[4];
63static bool quote_ignores_source_dir;
64enum { REASON_QUIET = 0, REASON_NOENT, REASON_DUP, REASON_DUP_SYS };
65
66/* Free an element of the include chain, possibly giving a reason.  */
67static void
68free_path (struct cpp_dir *path, int reason)
69{
70  switch (reason)
71    {
72    case REASON_DUP:
73    case REASON_DUP_SYS:
74      fprintf (stderr, _("ignoring duplicate directory \"%s\"\n"), path->name);
75      if (reason == REASON_DUP_SYS)
76	fprintf (stderr,
77 _("  as it is a non-system directory that duplicates a system directory\n"));
78      break;
79
80    case REASON_NOENT:
81      fprintf (stderr, _("ignoring nonexistent directory \"%s\"\n"),
82	       path->name);
83      break;
84
85    case REASON_QUIET:
86    default:
87      break;
88    }
89
90  free (path->name);
91  free (path);
92}
93
94/* Read ENV_VAR for a PATH_SEPARATOR-separated list of file names; and
95   append all the names to the search path CHAIN.  */
96static void
97add_env_var_paths (const char *env_var, int chain)
98{
99  char *p, *q, *path;
100
101  q = getenv (env_var);
102
103  if (!q)
104    return;
105
106  for (p = q; *q; p = q + 1)
107    {
108      q = p;
109      while (*q != 0 && *q != PATH_SEPARATOR)
110	q++;
111
112      if (p == q)
113	path = xstrdup (".");
114      else
115	{
116	  path = XNEWVEC (char, q - p + 1);
117	  memcpy (path, p, q - p);
118	  path[q - p] = '\0';
119	}
120
121      add_path (path, chain, chain == SYSTEM, false);
122    }
123}
124
125/* Append the standard include chain defined in cppdefault.c.  */
126static void
127add_standard_paths (const char *sysroot, const char *iprefix,
128		    const char *imultilib, int cxx_stdinc)
129{
130  const struct default_include *p;
131  int relocated = cpp_relocated ();
132  size_t len;
133
134  if (iprefix && (len = cpp_GCC_INCLUDE_DIR_len) != 0)
135    {
136      /* Look for directories that start with the standard prefix.
137	 "Translate" them, i.e. replace /usr/local/lib/gcc... with
138	 IPREFIX and search them first.  */
139      for (p = cpp_include_defaults; p->fname; p++)
140	{
141	  if (!p->cplusplus || cxx_stdinc)
142	    {
143	      /* Should we be translating sysrooted dirs too?  Assume
144		 that iprefix and sysroot are mutually exclusive, for
145		 now.  */
146	      if (sysroot && p->add_sysroot)
147		continue;
148	      if (!filename_ncmp (p->fname, cpp_GCC_INCLUDE_DIR, len))
149		{
150		  char *str = concat (iprefix, p->fname + len, NULL);
151		  if (p->multilib == 1 && imultilib)
152		    str = reconcat (str, str, dir_separator_str,
153				    imultilib, NULL);
154		  else if (p->multilib == 2)
155		    {
156		      if (!imultiarch)
157			{
158			  free (str);
159			  continue;
160			}
161		      str = reconcat (str, str, dir_separator_str,
162				      imultiarch, NULL);
163		    }
164		  add_path (str, SYSTEM, p->cxx_aware, false);
165		}
166	    }
167	}
168    }
169
170  for (p = cpp_include_defaults; p->fname; p++)
171    {
172      if (!p->cplusplus || cxx_stdinc)
173	{
174	  char *str;
175
176	  /* Should this directory start with the sysroot?  */
177	  if (sysroot && p->add_sysroot)
178	    {
179	      char *sysroot_no_trailing_dir_separator = xstrdup (sysroot);
180	      size_t sysroot_len = strlen (sysroot);
181
182	      if (sysroot_len > 0 && sysroot[sysroot_len - 1] == DIR_SEPARATOR)
183		sysroot_no_trailing_dir_separator[sysroot_len - 1] = '\0';
184	      str = concat (sysroot_no_trailing_dir_separator, p->fname, NULL);
185	      free (sysroot_no_trailing_dir_separator);
186	    }
187	  else if (!p->add_sysroot && relocated
188		   && !filename_ncmp (p->fname, cpp_PREFIX, cpp_PREFIX_len))
189	    {
190 	      static const char *relocated_prefix;
191	      char *ostr;
192	      /* If this path starts with the configure-time prefix,
193		 but the compiler has been relocated, replace it
194		 with the run-time prefix.  The run-time exec prefix
195		 is GCC_EXEC_PREFIX.  Compute the path from there back
196		 to the toplevel prefix.  */
197	      if (!relocated_prefix)
198		{
199		  char *dummy;
200		  /* Make relative prefix expects the first argument
201		     to be a program, not a directory.  */
202		  dummy = concat (gcc_exec_prefix, "dummy", NULL);
203		  relocated_prefix
204		    = make_relative_prefix (dummy,
205					    cpp_EXEC_PREFIX,
206					    cpp_PREFIX);
207		  free (dummy);
208		}
209	      ostr = concat (relocated_prefix,
210			     p->fname + cpp_PREFIX_len,
211			     NULL);
212	      str = update_path (ostr, p->component);
213	      free (ostr);
214	    }
215	  else
216	    str = update_path (p->fname, p->component);
217
218	  if (p->multilib == 1 && imultilib)
219	    str = reconcat (str, str, dir_separator_str, imultilib, NULL);
220	  else if (p->multilib == 2)
221	    {
222	      if (!imultiarch)
223		{
224		  free (str);
225		  continue;
226		}
227	      str = reconcat (str, str, dir_separator_str, imultiarch, NULL);
228	    }
229
230	  add_path (str, SYSTEM, p->cxx_aware, false);
231	}
232    }
233}
234
235/* For each duplicate path in chain HEAD, keep just the first one.
236   Remove each path in chain HEAD that also exists in chain SYSTEM.
237   Set the NEXT pointer of the last path in the resulting chain to
238   JOIN, unless it duplicates JOIN in which case the last path is
239   removed.  Return the head of the resulting chain.  Any of HEAD,
240   JOIN and SYSTEM can be NULL.  */
241
242static struct cpp_dir *
243remove_duplicates (cpp_reader *pfile, struct cpp_dir *head,
244		   struct cpp_dir *system, struct cpp_dir *join,
245		   int verbose)
246{
247  struct cpp_dir **pcur, *tmp, *cur;
248  struct stat st;
249
250  for (pcur = &head; *pcur; )
251    {
252      int reason = REASON_QUIET;
253
254      cur = *pcur;
255
256      if (stat (cur->name, &st))
257	{
258	  /* Dirs that don't exist are silently ignored, unless verbose.  */
259	  if (errno != ENOENT)
260	    cpp_errno (pfile, CPP_DL_ERROR, cur->name);
261	  else
262	    {
263	      /* If -Wmissing-include-dirs is given, warn.  */
264	      cpp_options *opts = cpp_get_options (pfile);
265	      if (opts->warn_missing_include_dirs && cur->user_supplied_p)
266		cpp_warning (pfile, CPP_W_MISSING_INCLUDE_DIRS, "%s: %s",
267			     cur->name, xstrerror (errno));
268	      reason = REASON_NOENT;
269	    }
270	}
271      else if (!S_ISDIR (st.st_mode))
272	cpp_error_with_line (pfile, CPP_DL_WARNING, 0, 0,
273			     "%s: not a directory", cur->name);
274      else
275	{
276#if defined (INO_T_COPY)
277	  INO_T_COPY (cur->ino, st.st_ino);
278	  cur->dev  = st.st_dev;
279#endif
280
281	  /* Remove this one if it is in the system chain.  */
282	  reason = REASON_DUP_SYS;
283	  for (tmp = system; tmp; tmp = tmp->next)
284	   if (DIRS_EQ (tmp, cur) && cur->construct == tmp->construct)
285	      break;
286
287	  if (!tmp)
288	    {
289	      /* Duplicate of something earlier in the same chain?  */
290	      reason = REASON_DUP;
291	      for (tmp = head; tmp != cur; tmp = tmp->next)
292	       if (DIRS_EQ (cur, tmp) && cur->construct == tmp->construct)
293		  break;
294
295	      if (tmp == cur
296		  /* Last in the chain and duplicate of JOIN?  */
297		  && !(cur->next == NULL && join
298		       && DIRS_EQ (cur, join)
299		       && cur->construct == join->construct))
300		{
301		  /* Unique, so keep this directory.  */
302		  pcur = &cur->next;
303		  continue;
304		}
305	    }
306	}
307
308      /* Remove this entry from the chain.  */
309      *pcur = cur->next;
310      free_path (cur, verbose ? reason: REASON_QUIET);
311    }
312
313  *pcur = join;
314  return head;
315}
316
317/* Add SYSROOT to any user-supplied paths in CHAIN starting with
318   "=".  */
319
320static void
321add_sysroot_to_chain (const char *sysroot, int chain)
322{
323  struct cpp_dir *p;
324
325  for (p = heads[chain]; p != NULL; p = p->next)
326    if (p->name[0] == '=' && p->user_supplied_p)
327      p->name = concat (sysroot, p->name + 1, NULL);
328}
329
330/* Merge the four include chains together in the order quote, bracket,
331   system, after.  Remove duplicate dirs (determined in
332   system-specific manner).
333
334   We can't just merge the lists and then uniquify them because then
335   we may lose directories from the <> search path that should be
336   there; consider -iquote foo -iquote bar -Ifoo -Iquux.  It is
337   however safe to treat -iquote bar -iquote foo -Ifoo -Iquux as if
338   written -iquote bar -Ifoo -Iquux.  */
339
340static void
341merge_include_chains (const char *sysroot, cpp_reader *pfile, int verbose)
342{
343  /* Add the sysroot to user-supplied paths starting with "=".  */
344  if (sysroot)
345    {
346      add_sysroot_to_chain (sysroot, QUOTE);
347      add_sysroot_to_chain (sysroot, BRACKET);
348      add_sysroot_to_chain (sysroot, SYSTEM);
349      add_sysroot_to_chain (sysroot, AFTER);
350    }
351
352  /* Join the SYSTEM and AFTER chains.  Remove duplicates in the
353     resulting SYSTEM chain.  */
354  if (heads[SYSTEM])
355    tails[SYSTEM]->next = heads[AFTER];
356  else
357    heads[SYSTEM] = heads[AFTER];
358  heads[SYSTEM] = remove_duplicates (pfile, heads[SYSTEM], 0, 0, verbose);
359
360  /* Remove duplicates from BRACKET that are in itself or SYSTEM, and
361     join it to SYSTEM.  */
362  heads[BRACKET] = remove_duplicates (pfile, heads[BRACKET], heads[SYSTEM],
363				      heads[SYSTEM], verbose);
364
365  /* Remove duplicates from QUOTE that are in itself or SYSTEM, and
366     join it to BRACKET.  */
367  heads[QUOTE] = remove_duplicates (pfile, heads[QUOTE], heads[SYSTEM],
368				    heads[BRACKET], verbose);
369
370  /* If verbose, print the list of dirs to search.  */
371  if (verbose)
372    {
373      struct cpp_dir *p;
374
375      fprintf (stderr, _("#include \"...\" search starts here:\n"));
376      for (p = heads[QUOTE];; p = p->next)
377	{
378	  if (p == heads[BRACKET])
379	    fprintf (stderr, _("#include <...> search starts here:\n"));
380	  if (!p)
381	    break;
382	  fprintf (stderr, " %s\n", p->name);
383	}
384      fprintf (stderr, _("End of search list.\n"));
385    }
386}
387
388/* Use given -I paths for #include "..." but not #include <...>, and
389   don't search the directory of the present file for #include "...".
390   (Note that -I. -I- is not the same as the default setup; -I. uses
391   the compiler's working dir.)  */
392void
393split_quote_chain (void)
394{
395  if (heads[QUOTE])
396    free_path (heads[QUOTE], REASON_QUIET);
397  if (tails[QUOTE])
398    free_path (tails[QUOTE], REASON_QUIET);
399  heads[QUOTE] = heads[BRACKET];
400  tails[QUOTE] = tails[BRACKET];
401  heads[BRACKET] = NULL;
402  tails[BRACKET] = NULL;
403  /* This is NOT redundant.  */
404  quote_ignores_source_dir = true;
405}
406
407/* Add P to the chain specified by CHAIN.  */
408
409void
410add_cpp_dir_path (cpp_dir *p, int chain)
411{
412  if (tails[chain])
413    tails[chain]->next = p;
414  else
415    heads[chain] = p;
416  tails[chain] = p;
417}
418
419/* Add PATH to the include chain CHAIN. PATH must be malloc-ed and
420   NUL-terminated.  */
421void
422add_path (char *path, int chain, int cxx_aware, bool user_supplied_p)
423{
424  cpp_dir *p;
425
426#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
427  /* Remove unnecessary trailing slashes.  On some versions of MS
428     Windows, trailing  _forward_ slashes cause no problems for stat().
429     On newer versions, stat() does not recognize a directory that ends
430     in a '\\' or '/', unless it is a drive root dir, such as "c:/",
431     where it is obligatory.  */
432  int pathlen = strlen (path);
433  char* end = path + pathlen - 1;
434  /* Preserve the lead '/' or lead "c:/".  */
435  char* start = path + (pathlen > 2 && path[1] == ':' ? 3 : 1);
436
437  for (; end > start && IS_DIR_SEPARATOR (*end); end--)
438    *end = 0;
439#endif
440
441  p = XNEW (cpp_dir);
442  p->next = NULL;
443  p->name = path;
444#ifndef INO_T_EQ
445  p->canonical_name = lrealpath (path);
446#endif
447  if (chain == SYSTEM || chain == AFTER)
448    p->sysp = 1 + !cxx_aware;
449  else
450    p->sysp = 0;
451  p->construct = 0;
452  p->user_supplied_p = user_supplied_p;
453
454  add_cpp_dir_path (p, chain);
455}
456
457/* Exported function to handle include chain merging, duplicate
458   removal, and registration with cpplib.  */
459void
460register_include_chains (cpp_reader *pfile, const char *sysroot,
461			 const char *iprefix, const char *imultilib,
462			 int stdinc, int cxx_stdinc, int verbose)
463{
464  static const char *const lang_env_vars[] =
465    { "C_INCLUDE_PATH", "CPLUS_INCLUDE_PATH",
466      "OBJC_INCLUDE_PATH", "OBJCPLUS_INCLUDE_PATH" };
467  cpp_options *cpp_opts = cpp_get_options (pfile);
468  size_t idx = (cpp_opts->objc ? 2: 0);
469
470  if (cpp_opts->cplusplus)
471    idx++;
472  else
473    cxx_stdinc = false;
474
475  /* CPATH and language-dependent environment variables may add to the
476     include chain.  */
477  add_env_var_paths ("CPATH", BRACKET);
478  add_env_var_paths (lang_env_vars[idx], SYSTEM);
479
480  target_c_incpath.extra_pre_includes (sysroot, iprefix, stdinc);
481
482  /* Finally chain on the standard directories.  */
483  if (stdinc)
484    add_standard_paths (sysroot, iprefix, imultilib, cxx_stdinc);
485
486  target_c_incpath.extra_includes (sysroot, iprefix, stdinc);
487
488  merge_include_chains (sysroot, pfile, verbose);
489
490  cpp_set_include_chains (pfile, heads[QUOTE], heads[BRACKET],
491			  quote_ignores_source_dir);
492}
493
494/* Return the current chain of cpp dirs.  */
495
496struct cpp_dir *
497get_added_cpp_dirs (int chain)
498{
499  return heads[chain];
500}
501
502#if !(defined TARGET_EXTRA_INCLUDES) || !(defined TARGET_EXTRA_PRE_INCLUDES)
503static void hook_void_charptr_charptr_int (const char *sysroot ATTRIBUTE_UNUSED,
504					   const char *iprefix ATTRIBUTE_UNUSED,
505					   int stdinc ATTRIBUTE_UNUSED)
506{
507}
508#endif
509
510#ifndef TARGET_EXTRA_INCLUDES
511#define TARGET_EXTRA_INCLUDES hook_void_charptr_charptr_int
512#endif
513#ifndef TARGET_EXTRA_PRE_INCLUDES
514#define TARGET_EXTRA_PRE_INCLUDES hook_void_charptr_charptr_int
515#endif
516
517struct target_c_incpath_s target_c_incpath = { TARGET_EXTRA_PRE_INCLUDES, TARGET_EXTRA_INCLUDES };
518
519