InitHeaderSearch.cpp revision 195341
1//===--- InitHeaderSearch.cpp - Initialize header search paths ----------*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the InitHeaderSearch class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/InitHeaderSearch.h"
15#include "clang/Lex/HeaderSearch.h"
16#include "clang/Basic/FileManager.h"
17#include "clang/Basic/LangOptions.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/System/Path.h"
21#include "llvm/Config/config.h"
22#include <cstdio>
23#include <vector>
24using namespace clang;
25
26void InitHeaderSearch::AddPath(const std::string &Path, IncludeDirGroup Group,
27                               bool isCXXAware, bool isUserSupplied,
28                               bool isFramework, bool IgnoreSysRoot) {
29  assert(!Path.empty() && "can't handle empty path here");
30  FileManager &FM = Headers.getFileMgr();
31
32  // Compute the actual path, taking into consideration -isysroot.
33  llvm::SmallString<256> MappedPath;
34
35  // Handle isysroot.
36  if (Group == System && !IgnoreSysRoot) {
37    // FIXME: Portability.  This should be a sys::Path interface, this doesn't
38    // handle things like C:\ right, nor win32 \\network\device\blah.
39    if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
40      MappedPath.append(isysroot.begin(), isysroot.end());
41  }
42
43  MappedPath.append(Path.begin(), Path.end());
44
45  // Compute the DirectoryLookup type.
46  SrcMgr::CharacteristicKind Type;
47  if (Group == Quoted || Group == Angled)
48    Type = SrcMgr::C_User;
49  else if (isCXXAware)
50    Type = SrcMgr::C_System;
51  else
52    Type = SrcMgr::C_ExternCSystem;
53
54
55  // If the directory exists, add it.
56  if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
57                                                 &MappedPath[0]+
58                                                 MappedPath.size())) {
59    IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
60                                                  isFramework));
61    return;
62  }
63
64  // Check to see if this is an apple-style headermap (which are not allowed to
65  // be frameworks).
66  if (!isFramework) {
67    if (const FileEntry *FE = FM.getFile(&MappedPath[0],
68                                         &MappedPath[0]+MappedPath.size())) {
69      if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) {
70        // It is a headermap, add it to the search path.
71        IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
72        return;
73      }
74    }
75  }
76
77  if (Verbose)
78    fprintf(stderr, "ignoring nonexistent directory \"%s\"\n",
79            MappedPath.c_str());
80}
81
82
83void InitHeaderSearch::AddEnvVarPaths(const char *Name) {
84  const char* at = getenv(Name);
85  if (!at || *at == 0) // Empty string should not add '.' path.
86    return;
87
88  const char* delim = strchr(at, llvm::sys::PathSeparator);
89  while (delim != 0) {
90    if (delim-at == 0)
91      AddPath(".", Angled, false, true, false);
92    else
93      AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
94              true, false);
95    at = delim + 1;
96    delim = strchr(at, llvm::sys::PathSeparator);
97  }
98  if (*at == 0)
99    AddPath(".", Angled, false, true, false);
100  else
101    AddPath(at, Angled, false, true, false);
102}
103
104
105void InitHeaderSearch::AddDefaultSystemIncludePaths(const LangOptions &Lang) {
106  // FIXME: temporary hack: hard-coded paths.
107  // FIXME: get these from the target?
108
109#ifdef LLVM_ON_WIN32
110  if (Lang.CPlusPlus) {
111    // Mingw32 GCC version 4
112    AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++",
113            System, true, false, false);
114    AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++/mingw32",
115            System, true, false, false);
116    AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++/backward",
117            System, true, false, false);
118  }
119
120  // Mingw32 GCC version 4
121  AddPath("C:/mingw/include", System, false, false, false);
122#else
123
124  if (Lang.CPlusPlus) {
125    AddPath("/usr/include/c++/4.2.1", System, true, false, false);
126    AddPath("/usr/include/c++/4.2.1/i686-apple-darwin10", System, true, false,
127        false);
128    AddPath("/usr/include/c++/4.2.1/backward", System, true, false, false);
129
130    AddPath("/usr/include/c++/4.0.0", System, true, false, false);
131    AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
132        false);
133    AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false);
134
135    // Ubuntu 7.10 - Gutsy Gibbon
136    AddPath("/usr/include/c++/4.1.3", System, true, false, false);
137    AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
138        false);
139    AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false);
140
141    // Ubuntu 9.04
142    AddPath("/usr/include/c++/4.3.3", System, true, false, false);
143    AddPath("/usr/include/c++/4.3.3/x86_64-linux-gnu/", System, true, false,
144        false);
145    AddPath("/usr/include/c++/4.3.3/backward", System, true, false, false);
146
147    // Fedora 8
148    AddPath("/usr/include/c++/4.1.2", System, true, false, false);
149    AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false,
150        false);
151    AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false);
152
153    // Fedora 9
154    AddPath("/usr/include/c++/4.3.0", System, true, false, false);
155    AddPath("/usr/include/c++/4.3.0/i386-redhat-linux", System, true, false,
156        false);
157    AddPath("/usr/include/c++/4.3.0/backward", System, true, false, false);
158
159    // Fedora 10
160    AddPath("/usr/include/c++/4.3.2", System, true, false, false);
161    AddPath("/usr/include/c++/4.3.2/i386-redhat-linux", System, true, false,
162        false);
163    AddPath("/usr/include/c++/4.3.2/backward", System, true, false, false);
164
165    // Arch Linux 2008-06-24
166    AddPath("/usr/include/c++/4.3.1", System, true, false, false);
167    AddPath("/usr/include/c++/4.3.1/i686-pc-linux-gnu", System, true, false,
168        false);
169    AddPath("/usr/include/c++/4.3.1/backward", System, true, false, false);
170    AddPath("/usr/include/c++/4.3.1/x86_64-unknown-linux-gnu", System, true,
171        false, false);
172
173    // Gentoo x86 stable
174    AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4", System,
175            true, false, false);
176    AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/"
177            "i686-pc-linux-gnu", System, true, false, false);
178    AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/backward",
179            System, true, false, false);
180
181    // Gentoo amd64 stable
182    AddPath("/usr/lib/gcc/x86_64-pc-linux-gnu/4.1.2/include/g++-v4", System,
183            true, false, false);
184    AddPath("/usr/lib/gcc/x86_64-pc-linux-gnu/4.1.2/include/g++-v4/"
185            "i686-pc-linux-gnu", System, true, false, false);
186    AddPath("/usr/lib/gcc/x86_64-pc-linux-gnu/4.1.2/include/g++-v4/backward",
187            System, true, false, false);
188
189    // DragonFly
190    AddPath("/usr/include/c++/4.1", System, true, false, false);
191
192    // FreeBSD
193    AddPath("/usr/include/c++/4.2", System, true, false, false);
194  }
195
196  AddPath("/usr/local/include", System, false, false, false);
197
198  AddPath("/usr/include", System, false, false, false);
199  AddPath("/System/Library/Frameworks", System, true, false, true);
200  AddPath("/Library/Frameworks", System, true, false, true);
201#endif
202}
203
204void InitHeaderSearch::AddDefaultEnvVarPaths(const LangOptions &Lang) {
205  AddEnvVarPaths("CPATH");
206  if (Lang.CPlusPlus && Lang.ObjC1)
207    AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH");
208  else if (Lang.CPlusPlus)
209    AddEnvVarPaths("CPLUS_INCLUDE_PATH");
210  else if (Lang.ObjC1)
211    AddEnvVarPaths("OBJC_INCLUDE_PATH");
212  else
213    AddEnvVarPaths("C_INCLUDE_PATH");
214}
215
216
217/// RemoveDuplicates - If there are duplicate directory entries in the specified
218/// search list, remove the later (dead) ones.
219static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList,
220                             bool Verbose) {
221  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
222  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
223  llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
224  for (unsigned i = 0; i != SearchList.size(); ++i) {
225    unsigned DirToRemove = i;
226
227    const DirectoryLookup &CurEntry = SearchList[i];
228
229    if (CurEntry.isNormalDir()) {
230      // If this isn't the first time we've seen this dir, remove it.
231      if (SeenDirs.insert(CurEntry.getDir()))
232        continue;
233    } else if (CurEntry.isFramework()) {
234      // If this isn't the first time we've seen this framework dir, remove it.
235      if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir()))
236        continue;
237    } else {
238      assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
239      // If this isn't the first time we've seen this headermap, remove it.
240      if (SeenHeaderMaps.insert(CurEntry.getHeaderMap()))
241        continue;
242    }
243
244    // If we have a normal #include dir/framework/headermap that is shadowed
245    // later in the chain by a system include location, we actually want to
246    // ignore the user's request and drop the user dir... keeping the system
247    // dir.  This is weird, but required to emulate GCC's search path correctly.
248    //
249    // Since dupes of system dirs are rare, just rescan to find the original
250    // that we're nuking instead of using a DenseMap.
251    if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) {
252      // Find the dir that this is the same of.
253      unsigned FirstDir;
254      for (FirstDir = 0; ; ++FirstDir) {
255        assert(FirstDir != i && "Didn't find dupe?");
256
257        const DirectoryLookup &SearchEntry = SearchList[FirstDir];
258
259        // If these are different lookup types, then they can't be the dupe.
260        if (SearchEntry.getLookupType() != CurEntry.getLookupType())
261          continue;
262
263        bool isSame;
264        if (CurEntry.isNormalDir())
265          isSame = SearchEntry.getDir() == CurEntry.getDir();
266        else if (CurEntry.isFramework())
267          isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir();
268        else {
269          assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
270          isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap();
271        }
272
273        if (isSame)
274          break;
275      }
276
277      // If the first dir in the search path is a non-system dir, zap it
278      // instead of the system one.
279      if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User)
280        DirToRemove = FirstDir;
281    }
282
283    if (Verbose) {
284      fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
285              CurEntry.getName());
286      if (DirToRemove != i)
287        fprintf(stderr, "  as it is a non-system directory that duplicates"
288                " a system directory\n");
289    }
290
291    // This is reached if the current entry is a duplicate.  Remove the
292    // DirToRemove (usually the current dir).
293    SearchList.erase(SearchList.begin()+DirToRemove);
294    --i;
295  }
296}
297
298
299void InitHeaderSearch::Realize() {
300  // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
301  std::vector<DirectoryLookup> SearchList;
302  SearchList = IncludeGroup[Angled];
303  SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
304                    IncludeGroup[System].end());
305  SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
306                    IncludeGroup[After].end());
307  RemoveDuplicates(SearchList, Verbose);
308  RemoveDuplicates(IncludeGroup[Quoted], Verbose);
309
310  // Prepend QUOTED list on the search list.
311  SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
312                    IncludeGroup[Quoted].end());
313
314
315  bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
316  Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
317                         DontSearchCurDir);
318
319  // If verbose, print the list of directories that will be searched.
320  if (Verbose) {
321    fprintf(stderr, "#include \"...\" search starts here:\n");
322    unsigned QuotedIdx = IncludeGroup[Quoted].size();
323    for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
324      if (i == QuotedIdx)
325        fprintf(stderr, "#include <...> search starts here:\n");
326      const char *Name = SearchList[i].getName();
327      const char *Suffix;
328      if (SearchList[i].isNormalDir())
329        Suffix = "";
330      else if (SearchList[i].isFramework())
331        Suffix = " (framework directory)";
332      else {
333        assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
334        Suffix = " (headermap)";
335      }
336      fprintf(stderr, " %s%s\n", Name, Suffix);
337    }
338    fprintf(stderr, "End of search list.\n");
339  }
340}
341
342