1 //===--- HeaderSearch.cpp - Resolve Header File Locations ---===// 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 DirectoryLookup and HeaderSearch interfaces. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Lex/HeaderSearch.h" 15 #include "clang/Lex/HeaderMap.h" 16 #include "clang/Basic/FileManager.h" 17 #include "clang/Basic/IdentifierTable.h" 18 #include "llvm/System/Path.h" 19 #include "llvm/ADT/SmallString.h" 20 #include <cstdio> 21 using namespace clang; 22 23 const IdentifierInfo * 24 HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) { 25 if (ControllingMacro) 26 return ControllingMacro; 27 28 if (!ControllingMacroID || !External) 29 return 0; 30 31 ControllingMacro = External->GetIdentifier(ControllingMacroID); 32 return ControllingMacro; 33 } 34 35 HeaderSearch::HeaderSearch(FileManager &FM) : FileMgr(FM), FrameworkMap(64) { 36 SystemDirIdx = 0; 37 NoCurDirSearch = false; 38 39 ExternalLookup = 0; 40 NumIncluded = 0; 41 NumMultiIncludeFileOptzn = 0; 42 NumFrameworkLookups = NumSubFrameworkLookups = 0; 43 } 44 45 HeaderSearch::~HeaderSearch() { 46 // Delete headermaps. 47 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i) 48 delete HeaderMaps[i].second; 49 } 50 51 void HeaderSearch::PrintStats() { 52 fprintf(stderr, "\n*** HeaderSearch Stats:\n"); 53 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size()); 54 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0; 55 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) { 56 NumOnceOnlyFiles += FileInfo[i].isImport; 57 if (MaxNumIncludes < FileInfo[i].NumIncludes) 58 MaxNumIncludes = FileInfo[i].NumIncludes; 59 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1; 60 } 61 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles); 62 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles); 63 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes); 64 65 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded); 66 fprintf(stderr, " %d #includes skipped due to" 67 " the multi-include optimization.\n", NumMultiIncludeFileOptzn); 68 69 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups); 70 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups); 71 } 72 73 /// CreateHeaderMap - This method returns a HeaderMap for the specified 74 /// FileEntry, uniquing them through the the 'HeaderMaps' datastructure. 75 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) { 76 // We expect the number of headermaps to be small, and almost always empty. 77 // If it ever grows, use of a linear search should be re-evaluated. 78 if (!HeaderMaps.empty()) { 79 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i) 80 // Pointer equality comparison of FileEntries works because they are 81 // already uniqued by inode. 82 if (HeaderMaps[i].first == FE) 83 return HeaderMaps[i].second; 84 } 85 86 if (const HeaderMap *HM = HeaderMap::Create(FE)) { 87 HeaderMaps.push_back(std::make_pair(FE, HM)); 88 return HM; 89 } 90 91 return 0; 92 } 93 94 //===----------------------------------------------------------------------===// 95 // File lookup within a DirectoryLookup scope 96 //===----------------------------------------------------------------------===// 97 98 /// getName - Return the directory or filename corresponding to this lookup 99 /// object. 100 const char *DirectoryLookup::getName() const { 101 if (isNormalDir()) 102 return getDir()->getName(); 103 if (isFramework()) 104 return getFrameworkDir()->getName(); 105 assert(isHeaderMap() && "Unknown DirectoryLookup"); 106 return getHeaderMap()->getFileName(); 107 } 108 109 110 /// LookupFile - Lookup the specified file in this search path, returning it 111 /// if it exists or returning null if not. 112 const FileEntry *DirectoryLookup::LookupFile(const char *FilenameStart, 113 const char *FilenameEnd, 114 HeaderSearch &HS) const { 115 llvm::SmallString<1024> TmpDir; 116 if (isNormalDir()) { 117 // Concatenate the requested file onto the directory. 118 // FIXME: Portability. Filename concatenation should be in sys::Path. 119 TmpDir += getDir()->getName(); 120 TmpDir.push_back('/'); 121 TmpDir.append(FilenameStart, FilenameEnd); 122 return HS.getFileMgr().getFile(TmpDir.begin(), TmpDir.end()); 123 } 124 125 if (isFramework()) 126 return DoFrameworkLookup(FilenameStart, FilenameEnd, HS); 127 128 assert(isHeaderMap() && "Unknown directory lookup"); 129 return getHeaderMap()->LookupFile(FilenameStart, FilenameEnd,HS.getFileMgr()); 130 } 131 132 133 /// DoFrameworkLookup - Do a lookup of the specified file in the current 134 /// DirectoryLookup, which is a framework directory. 135 const FileEntry *DirectoryLookup::DoFrameworkLookup(const char *FilenameStart, 136 const char *FilenameEnd, 137 HeaderSearch &HS) const { 138 FileManager &FileMgr = HS.getFileMgr(); 139 140 // Framework names must have a '/' in the filename. 141 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/'); 142 if (SlashPos == FilenameEnd) return 0; 143 144 // Find out if this is the home for the specified framework, by checking 145 // HeaderSearch. Possible answer are yes/no and unknown. 146 const DirectoryEntry *&FrameworkDirCache = 147 HS.LookupFrameworkCache(FilenameStart, SlashPos); 148 149 // If it is known and in some other directory, fail. 150 if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir()) 151 return 0; 152 153 // Otherwise, construct the path to this framework dir. 154 155 // FrameworkName = "/System/Library/Frameworks/" 156 llvm::SmallString<1024> FrameworkName; 157 FrameworkName += getFrameworkDir()->getName(); 158 if (FrameworkName.empty() || FrameworkName.back() != '/') 159 FrameworkName.push_back('/'); 160 161 // FrameworkName = "/System/Library/Frameworks/Cocoa" 162 FrameworkName.append(FilenameStart, SlashPos); 163 164 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/" 165 FrameworkName += ".framework/"; 166 167 // If the cache entry is still unresolved, query to see if the cache entry is 168 // still unresolved. If so, check its existence now. 169 if (FrameworkDirCache == 0) { 170 HS.IncrementFrameworkLookupCount(); 171 172 // If the framework dir doesn't exist, we fail. 173 // FIXME: It's probably more efficient to query this with FileMgr.getDir. 174 if (!llvm::sys::Path(std::string(FrameworkName.begin(), 175 FrameworkName.end())).exists()) 176 return 0; 177 178 // Otherwise, if it does, remember that this is the right direntry for this 179 // framework. 180 FrameworkDirCache = getFrameworkDir(); 181 } 182 183 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h" 184 unsigned OrigSize = FrameworkName.size(); 185 186 FrameworkName += "Headers/"; 187 FrameworkName.append(SlashPos+1, FilenameEnd); 188 if (const FileEntry *FE = FileMgr.getFile(FrameworkName.begin(), 189 FrameworkName.end())) { 190 return FE; 191 } 192 193 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h" 194 const char *Private = "Private"; 195 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private, 196 Private+strlen(Private)); 197 return FileMgr.getFile(FrameworkName.begin(), FrameworkName.end()); 198 } 199 200 201 //===----------------------------------------------------------------------===// 202 // Header File Location. 203 //===----------------------------------------------------------------------===// 204 205 206 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file, 207 /// return null on failure. isAngled indicates whether the file reference is 208 /// for system #include's or not (i.e. using <> instead of ""). CurFileEnt, if 209 /// non-null, indicates where the #including file is, in case a relative search 210 /// is needed. 211 const FileEntry *HeaderSearch::LookupFile(const char *FilenameStart, 212 const char *FilenameEnd, 213 bool isAngled, 214 const DirectoryLookup *FromDir, 215 const DirectoryLookup *&CurDir, 216 const FileEntry *CurFileEnt) { 217 // If 'Filename' is absolute, check to see if it exists and no searching. 218 // FIXME: Portability. This should be a sys::Path interface, this doesn't 219 // handle things like C:\foo.txt right, nor win32 \\network\device\blah. 220 if (FilenameStart[0] == '/') { 221 CurDir = 0; 222 223 // If this was an #include_next "/absolute/file", fail. 224 if (FromDir) return 0; 225 226 // Otherwise, just return the file. 227 return FileMgr.getFile(FilenameStart, FilenameEnd); 228 } 229 230 // Step #0, unless disabled, check to see if the file is in the #includer's 231 // directory. This has to be based on CurFileEnt, not CurDir, because 232 // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and 233 // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h". 234 // This search is not done for <> headers. 235 if (CurFileEnt && !isAngled && !NoCurDirSearch) { 236 llvm::SmallString<1024> TmpDir; 237 // Concatenate the requested file onto the directory. 238 // FIXME: Portability. Filename concatenation should be in sys::Path. 239 TmpDir += CurFileEnt->getDir()->getName(); 240 TmpDir.push_back('/'); 241 TmpDir.append(FilenameStart, FilenameEnd); 242 if (const FileEntry *FE = FileMgr.getFile(TmpDir.begin(), TmpDir.end())) { 243 // Leave CurDir unset. 244 // This file is a system header or C++ unfriendly if the old file is. 245 // 246 // Note that the temporary 'DirInfo' is required here, as either call to 247 // getFileInfo could resize the vector and we don't want to rely on order 248 // of evaluation. 249 unsigned DirInfo = getFileInfo(CurFileEnt).DirInfo; 250 getFileInfo(FE).DirInfo = DirInfo; 251 return FE; 252 } 253 } 254 255 CurDir = 0; 256 257 // If this is a system #include, ignore the user #include locs. 258 unsigned i = isAngled ? SystemDirIdx : 0; 259 260 // If this is a #include_next request, start searching after the directory the 261 // file was found in. 262 if (FromDir) 263 i = FromDir-&SearchDirs[0]; 264 265 // Cache all of the lookups performed by this method. Many headers are 266 // multiply included, and the "pragma once" optimization prevents them from 267 // being relex/pp'd, but they would still have to search through a 268 // (potentially huge) series of SearchDirs to find it. 269 std::pair<unsigned, unsigned> &CacheLookup = 270 LookupFileCache.GetOrCreateValue(FilenameStart, FilenameEnd).getValue(); 271 272 // If the entry has been previously looked up, the first value will be 273 // non-zero. If the value is equal to i (the start point of our search), then 274 // this is a matching hit. 275 if (CacheLookup.first == i+1) { 276 // Skip querying potentially lots of directories for this lookup. 277 i = CacheLookup.second; 278 } else { 279 // Otherwise, this is the first query, or the previous query didn't match 280 // our search start. We will fill in our found location below, so prime the 281 // start point value. 282 CacheLookup.first = i+1; 283 } 284 285 // Check each directory in sequence to see if it contains this file. 286 for (; i != SearchDirs.size(); ++i) { 287 const FileEntry *FE = 288 SearchDirs[i].LookupFile(FilenameStart, FilenameEnd, *this); 289 if (!FE) continue; 290 291 CurDir = &SearchDirs[i]; 292 293 // This file is a system header or C++ unfriendly if the dir is. 294 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic(); 295 296 // Remember this location for the next lookup we do. 297 CacheLookup.second = i; 298 return FE; 299 } 300 301 // Otherwise, didn't find it. Remember we didn't find this. 302 CacheLookup.second = SearchDirs.size(); 303 return 0; 304 } 305 306 /// LookupSubframeworkHeader - Look up a subframework for the specified 307 /// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from 308 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox 309 /// is a subframework within Carbon.framework. If so, return the FileEntry 310 /// for the designated file, otherwise return null. 311 const FileEntry *HeaderSearch:: 312 LookupSubframeworkHeader(const char *FilenameStart, 313 const char *FilenameEnd, 314 const FileEntry *ContextFileEnt) { 315 assert(ContextFileEnt && "No context file?"); 316 317 // Framework names must have a '/' in the filename. Find it. 318 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/'); 319 if (SlashPos == FilenameEnd) return 0; 320 321 // Look up the base framework name of the ContextFileEnt. 322 const char *ContextName = ContextFileEnt->getName(); 323 324 // If the context info wasn't a framework, couldn't be a subframework. 325 const char *FrameworkPos = strstr(ContextName, ".framework/"); 326 if (FrameworkPos == 0) 327 return 0; 328 329 llvm::SmallString<1024> FrameworkName(ContextName, 330 FrameworkPos+strlen(".framework/")); 331 332 // Append Frameworks/HIToolbox.framework/ 333 FrameworkName += "Frameworks/"; 334 FrameworkName.append(FilenameStart, SlashPos); 335 FrameworkName += ".framework/"; 336 337 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup = 338 FrameworkMap.GetOrCreateValue(FilenameStart, SlashPos); 339 340 // Some other location? 341 if (CacheLookup.getValue() && 342 CacheLookup.getKeyLength() == FrameworkName.size() && 343 memcmp(CacheLookup.getKeyData(), &FrameworkName[0], 344 CacheLookup.getKeyLength()) != 0) 345 return 0; 346 347 // Cache subframework. 348 if (CacheLookup.getValue() == 0) { 349 ++NumSubFrameworkLookups; 350 351 // If the framework dir doesn't exist, we fail. 352 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.begin(), 353 FrameworkName.end()); 354 if (Dir == 0) return 0; 355 356 // Otherwise, if it does, remember that this is the right direntry for this 357 // framework. 358 CacheLookup.setValue(Dir); 359 } 360 361 const FileEntry *FE = 0; 362 363 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h" 364 llvm::SmallString<1024> HeadersFilename(FrameworkName); 365 HeadersFilename += "Headers/"; 366 HeadersFilename.append(SlashPos+1, FilenameEnd); 367 if (!(FE = FileMgr.getFile(HeadersFilename.begin(), 368 HeadersFilename.end()))) { 369 370 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h" 371 HeadersFilename = FrameworkName; 372 HeadersFilename += "PrivateHeaders/"; 373 HeadersFilename.append(SlashPos+1, FilenameEnd); 374 if (!(FE = FileMgr.getFile(HeadersFilename.begin(), HeadersFilename.end()))) 375 return 0; 376 } 377 378 // This file is a system header or C++ unfriendly if the old file is. 379 // 380 // Note that the temporary 'DirInfo' is required here, as either call to 381 // getFileInfo could resize the vector and we don't want to rely on order 382 // of evaluation. 383 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo; 384 getFileInfo(FE).DirInfo = DirInfo; 385 return FE; 386 } 387 388 //===----------------------------------------------------------------------===// 389 // File Info Management. 390 //===----------------------------------------------------------------------===// 391 392 393 /// getFileInfo - Return the HeaderFileInfo structure for the specified 394 /// FileEntry. 395 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) { 396 if (FE->getUID() >= FileInfo.size()) 397 FileInfo.resize(FE->getUID()+1); 398 return FileInfo[FE->getUID()]; 399 } 400 401 void HeaderSearch::setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID) { 402 if (UID >= FileInfo.size()) 403 FileInfo.resize(UID+1); 404 FileInfo[UID] = HFI; 405 } 406 407 /// ShouldEnterIncludeFile - Mark the specified file as a target of of a 408 /// #include, #include_next, or #import directive. Return false if #including 409 /// the file will have no effect or true if we should include it. 410 bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){ 411 ++NumIncluded; // Count # of attempted #includes. 412 413 // Get information about this file. 414 HeaderFileInfo &FileInfo = getFileInfo(File); 415 416 // If this is a #import directive, check that we have not already imported 417 // this header. 418 if (isImport) { 419 // If this has already been imported, don't import it again. 420 FileInfo.isImport = true; 421 422 // Has this already been #import'ed or #include'd? 423 if (FileInfo.NumIncludes) return false; 424 } else { 425 // Otherwise, if this is a #include of a file that was previously #import'd 426 // or if this is the second #include of a #pragma once file, ignore it. 427 if (FileInfo.isImport) 428 return false; 429 } 430 431 // Next, check to see if the file is wrapped with #ifndef guards. If so, and 432 // if the macro that guards it is defined, we know the #include has no effect. 433 if (const IdentifierInfo *ControllingMacro 434 = FileInfo.getControllingMacro(ExternalLookup)) 435 if (ControllingMacro->hasMacroDefinition()) { 436 ++NumMultiIncludeFileOptzn; 437 return false; 438 } 439 440 // Increment the number of times this file has been included. 441 ++FileInfo.NumIncludes; 442 443 return true; 444 } 445 446 447