InitHeaderSearch.cpp revision 2835511b72c361fa346767a65bd2df7b79f9b9f4
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/Support/raw_ostream.h"
21#include "llvm/System/Path.h"
22#include "llvm/Config/config.h"
23#include <cstdio>
24using namespace clang;
25
26void InitHeaderSearch::AddPath(const llvm::StringRef &Path,
27                               IncludeDirGroup Group, bool isCXXAware,
28                               bool isUserSupplied, bool isFramework,
29                               bool IgnoreSysRoot) {
30  assert(!Path.empty() && "can't handle empty path here");
31  FileManager &FM = Headers.getFileMgr();
32
33  // Compute the actual path, taking into consideration -isysroot.
34  llvm::SmallString<256> MappedPath;
35
36  // Handle isysroot.
37  if (Group == System && !IgnoreSysRoot) {
38    // FIXME: Portability.  This should be a sys::Path interface, this doesn't
39    // handle things like C:\ right, nor win32 \\network\device\blah.
40    if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
41      MappedPath.append(isysroot.begin(), isysroot.end());
42  }
43
44  MappedPath.append(Path.begin(), Path.end());
45
46  // Compute the DirectoryLookup type.
47  SrcMgr::CharacteristicKind Type;
48  if (Group == Quoted || Group == Angled)
49    Type = SrcMgr::C_User;
50  else if (isCXXAware)
51    Type = SrcMgr::C_System;
52  else
53    Type = SrcMgr::C_ExternCSystem;
54
55
56  // If the directory exists, add it.
57  if (const DirectoryEntry *DE = FM.getDirectory(MappedPath.str())) {
58    IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
59                                                  isFramework));
60    return;
61  }
62
63  // Check to see if this is an apple-style headermap (which are not allowed to
64  // be frameworks).
65  if (!isFramework) {
66    if (const FileEntry *FE = FM.getFile(MappedPath.str())) {
67      if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) {
68        // It is a headermap, add it to the search path.
69        IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
70        return;
71      }
72    }
73  }
74
75  if (Verbose)
76    llvm::errs() << "ignoring nonexistent directory \""
77                 << MappedPath.str() << "\"\n";
78}
79
80
81void InitHeaderSearch::AddEnvVarPaths(const char *Name) {
82  const char* at = getenv(Name);
83  if (!at || *at == 0) // Empty string should not add '.' path.
84    return;
85
86  const char* delim = strchr(at, llvm::sys::PathSeparator);
87  while (delim != 0) {
88    if (delim-at == 0)
89      AddPath(".", Angled, false, true, false);
90    else
91      AddPath(llvm::StringRef(at, delim-at), Angled, false, true, false);
92    at = delim + 1;
93    delim = strchr(at, llvm::sys::PathSeparator);
94  }
95  if (*at == 0)
96    AddPath(".", Angled, false, true, false);
97  else
98    AddPath(at, Angled, false, true, false);
99}
100
101void InitHeaderSearch::AddGnuCPlusPlusIncludePaths(std::string base,
102                                                   std::string arch) {
103    AddPath(base, System, true, false, false);
104    AddPath(base + "/" + arch, System, true, false, false);
105    AddPath(base + "/backward", System, true, false, false);
106}
107
108#if defined(LLVM_ON_WIN32)
109
110#if 0 // Yikes!  Can't include windows.h.
111  #if LLVM_ON_WIN32
112    #define WIN32_LEAN_AND_MEAN 1
113    #include <windows.h>
114  #endif
115
116  // Read Windows registry string.
117bool getWindowsRegistryString(const char *keyPath, const char *valueName,
118                       char *value, size_t maxLength) {
119  HKEY hRootKey = NULL;
120  HKEY hKey = NULL;
121  const char* subKey = NULL;
122  DWORD valueType;
123  DWORD valueSize = maxLength - 1;
124  bool returnValue = false;
125  if (strncmp(keyPath, "HKEY_CLASSES_ROOT\\", 18) == 0) {
126    hRootKey = HKEY_CLASSES_ROOT;
127    subKey = keyPath + 18;
128  }
129  else if (strncmp(keyPath, "HKEY_USERS\\", 11) == 0) {
130    hRootKey = HKEY_USERS;
131    subKey = keyPath + 11;
132  }
133  else if (strncmp(keyPath, "HKEY_LOCAL_MACHINE\\", 19) == 0) {
134    hRootKey = HKEY_LOCAL_MACHINE;
135    subKey = keyPath + 19;
136  }
137  else if (strncmp(keyPath, "HKEY_CURRENT_USER\\", 18) == 0) {
138    hRootKey = HKEY_CURRENT_USER;
139    subKey = keyPath + 18;
140  }
141  else
142    return(false);
143  long lResult = RegOpenKeyEx(hRootKey, subKey, 0, KEY_READ, &hKey);
144  if (lResult == ERROR_SUCCESS) {
145    lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType, (LPBYTE)value,
146                              &valueSize);
147    if (lResult == ERROR_SUCCESS)
148      returnValue = true;
149    RegCloseKey(kKey);
150  }
151  return(returnValue);
152}
153
154  // Get Visual Studio installation directory.
155bool getVisualStudioDir(std::string &path) {
156  char vs80comntools[256];
157  char vs90comntools[256];
158  const char* vscomntools = NULL;
159  bool has80 = getWindowsRegistryString(
160    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\8.0",
161    "InstallDir", vs80comntools, sizeof(vs80comntools) - 1);
162  bool has90 = getWindowsRegistryString(
163    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\9.0",
164    "InstallDir", vs90comntools, sizeof(vs90comntools) - 1);
165    // If we have both vc80 and vc90, pick version we were compiled with.
166  if (has80 && has90) {
167    #ifdef _MSC_VER
168      #if (_MSC_VER >= 1500)  // VC90
169          vscomntools = vs90comntools;
170      #elif (_MSC_VER == 1400) // VC80
171          vscomntools = vs80comntools;
172      #else
173          vscomntools = vs90comntools;
174      #endif
175    #else
176      vscomntools = vs90comntools;
177    #endif
178  }
179  else if (has90)
180    vscomntools = vs90comntools;
181  else if (has80)
182    vscomntools = vs80comntools;
183  else
184    return(false);
185  char *p = strstr(vscomntools, "\\Common7\\ide");
186  if (p)
187    *p = '\0';
188  path = vscomntools;
189  return(true);
190}
191#else
192
193  // Get Visual Studio installation directory.
194bool getVisualStudioDir(std::string &path) {
195  const char* vs90comntools = getenv("VS90COMNTOOLS");
196  const char* vs80comntools = getenv("VS80COMNTOOLS");
197  const char* vscomntools = NULL;
198    // If we have both vc80 and vc90, pick version we were compiled with.
199  if (vs90comntools && vs80comntools) {
200    #if (_MSC_VER >= 1500)  // VC90
201        vscomntools = vs90comntools;
202    #elif (_MSC_VER == 1400) // VC80
203        vscomntools = vs80comntools;
204    #else
205        vscomntools = vs90comntools;
206    #endif
207  }
208  else if (vs90comntools)
209    vscomntools = vs90comntools;
210  else if (vs80comntools)
211    vscomntools = vs80comntools;
212  else
213    return(false);
214  char *p = (char*)strstr(vscomntools, "\\Common7\\Tools");
215  if (p)
216    *p = '\0';
217  path = vscomntools;
218  return(true);
219}
220#endif
221
222#endif // LLVM_ON_WIN32
223
224void InitHeaderSearch::AddDefaultSystemIncludePaths(const LangOptions &Lang,
225                                               const llvm::Triple &triple) {
226  // FIXME: temporary hack: hard-coded paths.
227  llvm::Triple::OSType os = triple.getOS();
228
229  switch (os) {
230  case llvm::Triple::Win32:
231    {
232      #if defined(_MSC_VER)
233        std::string VSDir;
234        if (getVisualStudioDir(VSDir)) {
235          VSDir += "\\VC\\include";
236          AddPath(VSDir, System, false, false, false);
237        }
238        else {
239            // Default install paths.
240          AddPath("C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\include",
241            System, false, false, false);
242          AddPath("C:\\Program Files\\Microsoft Visual Studio 8\\VC\\include",
243            System, false, false, false);
244            // For some clang developers.
245          AddPath("G:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\include",
246            System, false, false, false);
247        }
248      #else
249          // Default install paths.
250        AddPath("/Program Files/Microsoft Visual Studio 9.0/VC/include",
251          System, false, false, false);
252        AddPath("/Program Files/Microsoft Visual Studio 8/VC/include",
253          System, false, false, false);
254      #endif
255    }
256    break;
257  case llvm::Triple::Cygwin:
258    if (Lang.CPlusPlus) {
259      AddPath("/lib/gcc/i686-pc-cygwin/3.4.4/include", System, false, false,
260              false);
261      AddPath("/lib/gcc/i686-pc-cygwin/3.4.4/include/c++", System, false, false,
262              false);
263    }
264    AddPath("/usr/include", System, false, false, false);
265    break;
266  case llvm::Triple::MinGW32:
267  case llvm::Triple::MinGW64:
268    if (Lang.CPlusPlus) {
269      // Try gcc 4.4.0
270      // FIXME: This can just use AddGnuCPlusPlusIncludePaths, right?
271      AddPath("c:/mingw/lib/gcc/mingw32/4.4.0/include/c++",
272              System, true, false, false);
273      AddPath("c:/mingw/lib/gcc/mingw32/4.4.0/include/c++/mingw32",
274              System, true, false, false);
275      AddPath("c:/mingw/lib/gcc/mingw32/4.4.0/include/c++/backward",
276              System, true, false, false);
277      // Try gcc 4.3.0
278      // FIXME: This can just use AddGnuCPlusPlusIncludePaths, right?
279      AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++",
280              System, true, false, false);
281      AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++/mingw32",
282              System, true, false, false);
283      AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++/backward",
284              System, true, false, false);
285    }
286    AddPath("c:/mingw/include", System, true, false, false);
287    break;
288  default:
289    if (Lang.CPlusPlus) {
290      switch (os) {
291        case llvm::Triple::Darwin:
292          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
293                                      "i686-apple-darwin10");
294          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
295                                      "i686-apple-darwin8");
296          break;
297        case llvm::Triple::Linux:
298          // Ubuntu 7.10 - Gutsy Gibbon
299          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.3",
300                                      "i486-linux-gnu");
301          // Ubuntu 9.04
302          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.3",
303                                      "x86_64-linux-gnu");
304          // Fedora 8
305          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.2",
306                                      "i386-redhat-linux");
307          // Fedora 9
308          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.0",
309                                      "i386-redhat-linux");
310          // Fedora 10
311          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.2",
312                                      "i386-redhat-linux");
313          // openSUSE 11.1
314          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
315                                      "i586-suse-linux");
316          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
317                                      "x86_64-suse-linux");
318          // openSUSE 11.2
319          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
320                                      "i586-suse-linux");
321          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
322                                      "x86_64-suse-linux");
323          // Arch Linux 2008-06-24
324          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
325                                      "i686-pc-linux-gnu");
326          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
327                                      "x86_64-unknown-linux-gnu");
328          // Gentoo x86 2009.0 stable
329          AddGnuCPlusPlusIncludePaths(
330             "/usr/lib/gcc/i686-pc-linux-gnu/4.3.2/include/g++-v4",
331             "i686-pc-linux-gnu");
332          // Gentoo x86 2008.0 stable
333          AddGnuCPlusPlusIncludePaths(
334             "/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4",
335             "i686-pc-linux-gnu");
336          // Ubuntu 8.10
337          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
338                                      "i486-pc-linux-gnu");
339          // Gentoo amd64 stable
340          AddGnuCPlusPlusIncludePaths(
341             "/usr/lib/gcc/x86_64-pc-linux-gnu/4.1.2/include/g++-v4",
342             "i686-pc-linux-gnu");
343          break;
344        case llvm::Triple::FreeBSD:
345          // DragonFly
346          AddPath("/usr/include/c++/4.1", System, true, false, false);
347          // FreeBSD
348          AddPath("/usr/include/c++/4.2", System, true, false, false);
349          break;
350        case llvm::Triple::Solaris:
351          // AuroraUX
352          AddGnuCPlusPlusIncludePaths("/Opt/gcc4/include/c++/4.2.4",
353                                      "i386-pc-solaris2.11");
354          break;
355        default:
356          break;
357      }
358    }
359
360    AddPath("/usr/local/include", System, false, false, false);
361
362    AddPath("/usr/include", System, false, false, false);
363    AddPath("/System/Library/Frameworks", System, true, false, true);
364    AddPath("/Library/Frameworks", System, true, false, true);
365    break;
366  }
367}
368
369void InitHeaderSearch::AddDefaultEnvVarPaths(const LangOptions &Lang) {
370  AddEnvVarPaths("CPATH");
371  if (Lang.CPlusPlus && Lang.ObjC1)
372    AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH");
373  else if (Lang.CPlusPlus)
374    AddEnvVarPaths("CPLUS_INCLUDE_PATH");
375  else if (Lang.ObjC1)
376    AddEnvVarPaths("OBJC_INCLUDE_PATH");
377  else
378    AddEnvVarPaths("C_INCLUDE_PATH");
379}
380
381
382/// RemoveDuplicates - If there are duplicate directory entries in the specified
383/// search list, remove the later (dead) ones.
384static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList,
385                             bool Verbose) {
386  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
387  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
388  llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
389  for (unsigned i = 0; i != SearchList.size(); ++i) {
390    unsigned DirToRemove = i;
391
392    const DirectoryLookup &CurEntry = SearchList[i];
393
394    if (CurEntry.isNormalDir()) {
395      // If this isn't the first time we've seen this dir, remove it.
396      if (SeenDirs.insert(CurEntry.getDir()))
397        continue;
398    } else if (CurEntry.isFramework()) {
399      // If this isn't the first time we've seen this framework dir, remove it.
400      if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir()))
401        continue;
402    } else {
403      assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
404      // If this isn't the first time we've seen this headermap, remove it.
405      if (SeenHeaderMaps.insert(CurEntry.getHeaderMap()))
406        continue;
407    }
408
409    // If we have a normal #include dir/framework/headermap that is shadowed
410    // later in the chain by a system include location, we actually want to
411    // ignore the user's request and drop the user dir... keeping the system
412    // dir.  This is weird, but required to emulate GCC's search path correctly.
413    //
414    // Since dupes of system dirs are rare, just rescan to find the original
415    // that we're nuking instead of using a DenseMap.
416    if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) {
417      // Find the dir that this is the same of.
418      unsigned FirstDir;
419      for (FirstDir = 0; ; ++FirstDir) {
420        assert(FirstDir != i && "Didn't find dupe?");
421
422        const DirectoryLookup &SearchEntry = SearchList[FirstDir];
423
424        // If these are different lookup types, then they can't be the dupe.
425        if (SearchEntry.getLookupType() != CurEntry.getLookupType())
426          continue;
427
428        bool isSame;
429        if (CurEntry.isNormalDir())
430          isSame = SearchEntry.getDir() == CurEntry.getDir();
431        else if (CurEntry.isFramework())
432          isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir();
433        else {
434          assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
435          isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap();
436        }
437
438        if (isSame)
439          break;
440      }
441
442      // If the first dir in the search path is a non-system dir, zap it
443      // instead of the system one.
444      if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User)
445        DirToRemove = FirstDir;
446    }
447
448    if (Verbose) {
449      fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
450              CurEntry.getName());
451      if (DirToRemove != i)
452        fprintf(stderr, "  as it is a non-system directory that duplicates"
453                " a system directory\n");
454    }
455
456    // This is reached if the current entry is a duplicate.  Remove the
457    // DirToRemove (usually the current dir).
458    SearchList.erase(SearchList.begin()+DirToRemove);
459    --i;
460  }
461}
462
463
464void InitHeaderSearch::Realize() {
465  // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
466  std::vector<DirectoryLookup> SearchList;
467  SearchList = IncludeGroup[Angled];
468  SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
469                    IncludeGroup[System].end());
470  SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
471                    IncludeGroup[After].end());
472  RemoveDuplicates(SearchList, Verbose);
473  RemoveDuplicates(IncludeGroup[Quoted], Verbose);
474
475  // Prepend QUOTED list on the search list.
476  SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
477                    IncludeGroup[Quoted].end());
478
479
480  bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
481  Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
482                         DontSearchCurDir);
483
484  // If verbose, print the list of directories that will be searched.
485  if (Verbose) {
486    fprintf(stderr, "#include \"...\" search starts here:\n");
487    unsigned QuotedIdx = IncludeGroup[Quoted].size();
488    for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
489      if (i == QuotedIdx)
490        fprintf(stderr, "#include <...> search starts here:\n");
491      const char *Name = SearchList[i].getName();
492      const char *Suffix;
493      if (SearchList[i].isNormalDir())
494        Suffix = "";
495      else if (SearchList[i].isFramework())
496        Suffix = " (framework directory)";
497      else {
498        assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
499        Suffix = " (headermap)";
500      }
501      fprintf(stderr, " %s%s\n", Name, Suffix);
502    }
503    fprintf(stderr, "End of search list.\n");
504  }
505}
506