InitHeaderSearch.cpp revision 43d8176d2e8e304b2d419fb0fe139cc07af80dea
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                                                    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      AddPath("c:/mingw/lib/gcc/mingw32/4.4.0/include/c++",
271              System, true, false, false);
272      AddPath("c:/mingw/lib/gcc/mingw32/4.4.0/include/c++/mingw32",
273              System, true, false, false);
274      AddPath("c:/mingw/lib/gcc/mingw32/4.4.0/include/c++/backward",
275              System, true, false, false);
276      // Try gcc 4.3.0
277      AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++",
278              System, true, false, false);
279      AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++/mingw32",
280              System, true, false, false);
281      AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++/backward",
282              System, true, false, false);
283    }
284    AddPath("c:/mingw/include", System, true, false, false);
285    break;
286  default:
287    if (Lang.CPlusPlus) {
288      switch (os) {
289        case llvm::Triple::Darwin:
290          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
291                                      "i686-apple-darwin10");
292          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
293                                      "i686-apple-darwin8");
294          break;
295        case llvm::Triple::Linux:
296          // Ubuntu 7.10 - Gutsy Gibbon
297          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.3",
298                                      "i486-linux-gnu");
299          // Ubuntu 9.04
300          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.3",
301                                      "x86_64-linux-gnu");
302          // Fedora 8
303          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.2",
304                                      "i386-redhat-linux");
305          // Fedora 9
306          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.0",
307                                      "i386-redhat-linux");
308          // Fedora 10
309          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.2",
310                                      "i386-redhat-linux");
311          // openSUSE 11.1
312          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
313                                      "i586-suse-linux");
314          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
315                                      "x86_64-suse-linux");
316          // openSUSE 11.2
317          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
318                                      "i586-suse-linux");
319          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
320                                      "x86_64-suse-linux");
321          // Arch Linux 2008-06-24
322          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
323                                      "i686-pc-linux-gnu");
324          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
325                                      "x86_64-unknown-linux-gnu");
326          // Gentoo x86 2009.0 stable
327          AddGnuCPlusPlusIncludePaths(
328             "/usr/lib/gcc/i686-pc-linux-gnu/4.3.2/include/g++-v4",
329             "i686-pc-linux-gnu");
330          // Gentoo x86 2008.0 stable
331          AddGnuCPlusPlusIncludePaths(
332             "/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4",
333             "i686-pc-linux-gnu");
334          // Ubuntu 8.10
335          AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
336                                      "i486-pc-linux-gnu");
337          // Gentoo amd64 stable
338          AddGnuCPlusPlusIncludePaths(
339             "/usr/lib/gcc/x86_64-pc-linux-gnu/4.1.2/include/g++-v4",
340             "i686-pc-linux-gnu");
341          break;
342        case llvm::Triple::FreeBSD:
343          // DragonFly
344          AddPath("/usr/include/c++/4.1", System, true, false, false);
345          // FreeBSD
346          AddPath("/usr/include/c++/4.2", System, true, false, false);
347          break;
348        case llvm::Triple::Solaris:
349          // AuroraUX
350          AddGnuCPlusPlusIncludePaths("/Opt/gcc4/include/c++/4.2.4",
351                                      "i386-pc-solaris2.11");
352          break;
353        default:
354          break;
355      }
356    }
357
358    AddPath("/usr/local/include", System, false, false, false);
359
360    AddPath("/usr/include", System, false, false, false);
361    AddPath("/System/Library/Frameworks", System, true, false, true);
362    AddPath("/Library/Frameworks", System, true, false, true);
363    break;
364  }
365}
366
367void InitHeaderSearch::AddDefaultEnvVarPaths(const LangOptions &Lang) {
368  AddEnvVarPaths("CPATH");
369  if (Lang.CPlusPlus && Lang.ObjC1)
370    AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH");
371  else if (Lang.CPlusPlus)
372    AddEnvVarPaths("CPLUS_INCLUDE_PATH");
373  else if (Lang.ObjC1)
374    AddEnvVarPaths("OBJC_INCLUDE_PATH");
375  else
376    AddEnvVarPaths("C_INCLUDE_PATH");
377}
378
379
380/// RemoveDuplicates - If there are duplicate directory entries in the specified
381/// search list, remove the later (dead) ones.
382static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList,
383                             bool Verbose) {
384  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
385  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
386  llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
387  for (unsigned i = 0; i != SearchList.size(); ++i) {
388    unsigned DirToRemove = i;
389
390    const DirectoryLookup &CurEntry = SearchList[i];
391
392    if (CurEntry.isNormalDir()) {
393      // If this isn't the first time we've seen this dir, remove it.
394      if (SeenDirs.insert(CurEntry.getDir()))
395        continue;
396    } else if (CurEntry.isFramework()) {
397      // If this isn't the first time we've seen this framework dir, remove it.
398      if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir()))
399        continue;
400    } else {
401      assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
402      // If this isn't the first time we've seen this headermap, remove it.
403      if (SeenHeaderMaps.insert(CurEntry.getHeaderMap()))
404        continue;
405    }
406
407    // If we have a normal #include dir/framework/headermap that is shadowed
408    // later in the chain by a system include location, we actually want to
409    // ignore the user's request and drop the user dir... keeping the system
410    // dir.  This is weird, but required to emulate GCC's search path correctly.
411    //
412    // Since dupes of system dirs are rare, just rescan to find the original
413    // that we're nuking instead of using a DenseMap.
414    if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) {
415      // Find the dir that this is the same of.
416      unsigned FirstDir;
417      for (FirstDir = 0; ; ++FirstDir) {
418        assert(FirstDir != i && "Didn't find dupe?");
419
420        const DirectoryLookup &SearchEntry = SearchList[FirstDir];
421
422        // If these are different lookup types, then they can't be the dupe.
423        if (SearchEntry.getLookupType() != CurEntry.getLookupType())
424          continue;
425
426        bool isSame;
427        if (CurEntry.isNormalDir())
428          isSame = SearchEntry.getDir() == CurEntry.getDir();
429        else if (CurEntry.isFramework())
430          isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir();
431        else {
432          assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
433          isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap();
434        }
435
436        if (isSame)
437          break;
438      }
439
440      // If the first dir in the search path is a non-system dir, zap it
441      // instead of the system one.
442      if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User)
443        DirToRemove = FirstDir;
444    }
445
446    if (Verbose) {
447      fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
448              CurEntry.getName());
449      if (DirToRemove != i)
450        fprintf(stderr, "  as it is a non-system directory that duplicates"
451                " a system directory\n");
452    }
453
454    // This is reached if the current entry is a duplicate.  Remove the
455    // DirToRemove (usually the current dir).
456    SearchList.erase(SearchList.begin()+DirToRemove);
457    --i;
458  }
459}
460
461
462void InitHeaderSearch::Realize() {
463  // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
464  std::vector<DirectoryLookup> SearchList;
465  SearchList = IncludeGroup[Angled];
466  SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
467                    IncludeGroup[System].end());
468  SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
469                    IncludeGroup[After].end());
470  RemoveDuplicates(SearchList, Verbose);
471  RemoveDuplicates(IncludeGroup[Quoted], Verbose);
472
473  // Prepend QUOTED list on the search list.
474  SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
475                    IncludeGroup[Quoted].end());
476
477
478  bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
479  Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
480                         DontSearchCurDir);
481
482  // If verbose, print the list of directories that will be searched.
483  if (Verbose) {
484    fprintf(stderr, "#include \"...\" search starts here:\n");
485    unsigned QuotedIdx = IncludeGroup[Quoted].size();
486    for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
487      if (i == QuotedIdx)
488        fprintf(stderr, "#include <...> search starts here:\n");
489      const char *Name = SearchList[i].getName();
490      const char *Suffix;
491      if (SearchList[i].isNormalDir())
492        Suffix = "";
493      else if (SearchList[i].isFramework())
494        Suffix = " (framework directory)";
495      else {
496        assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
497        Suffix = " (headermap)";
498      }
499      fprintf(stderr, " %s%s\n", Name, Suffix);
500    }
501    fprintf(stderr, "End of search list.\n");
502  }
503}
504