1 //===--- FileManager.cpp - File System Probing and Caching ----------------===// 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 FileManager interface. 11 // 12 //===----------------------------------------------------------------------===// 13 // 14 // TODO: This should index all interesting directories with dirent calls. 15 // getdirentries ? 16 // opendir/readdir_r/closedir ? 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "clang/Basic/FileManager.h" 21 #include "clang/Basic/FileSystemStatCache.h" 22 #include "clang/Frontend/PCHContainerOperations.h" 23 #include "llvm/ADT/SmallString.h" 24 #include "llvm/Config/llvm-config.h" 25 #include "llvm/Support/FileSystem.h" 26 #include "llvm/Support/MemoryBuffer.h" 27 #include "llvm/Support/Path.h" 28 #include "llvm/Support/raw_ostream.h" 29 #include <map> 30 #include <set> 31 #include <string> 32 #include <system_error> 33 34 using namespace clang; 35 36 /// NON_EXISTENT_DIR - A special value distinct from null that is used to 37 /// represent a dir name that doesn't exist on the disk. 38 #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1) 39 40 /// NON_EXISTENT_FILE - A special value distinct from null that is used to 41 /// represent a filename that doesn't exist on the disk. 42 #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1) 43 44 //===----------------------------------------------------------------------===// 45 // Common logic. 46 //===----------------------------------------------------------------------===// 47 48 FileManager::FileManager(const FileSystemOptions &FSO, 49 IntrusiveRefCntPtr<vfs::FileSystem> FS) 50 : FS(FS), FileSystemOpts(FSO), 51 SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) { 52 NumDirLookups = NumFileLookups = 0; 53 NumDirCacheMisses = NumFileCacheMisses = 0; 54 55 // If the caller doesn't provide a virtual file system, just grab the real 56 // file system. 57 if (!FS) 58 this->FS = vfs::getRealFileSystem(); 59 } 60 61 FileManager::~FileManager() { 62 for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i) 63 delete VirtualFileEntries[i]; 64 for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i) 65 delete VirtualDirectoryEntries[i]; 66 } 67 68 void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache, 69 bool AtBeginning) { 70 assert(statCache && "No stat cache provided?"); 71 if (AtBeginning || !StatCache.get()) { 72 statCache->setNextStatCache(std::move(StatCache)); 73 StatCache = std::move(statCache); 74 return; 75 } 76 77 FileSystemStatCache *LastCache = StatCache.get(); 78 while (LastCache->getNextStatCache()) 79 LastCache = LastCache->getNextStatCache(); 80 81 LastCache->setNextStatCache(std::move(statCache)); 82 } 83 84 void FileManager::removeStatCache(FileSystemStatCache *statCache) { 85 if (!statCache) 86 return; 87 88 if (StatCache.get() == statCache) { 89 // This is the first stat cache. 90 StatCache = StatCache->takeNextStatCache(); 91 return; 92 } 93 94 // Find the stat cache in the list. 95 FileSystemStatCache *PrevCache = StatCache.get(); 96 while (PrevCache && PrevCache->getNextStatCache() != statCache) 97 PrevCache = PrevCache->getNextStatCache(); 98 99 assert(PrevCache && "Stat cache not found for removal"); 100 PrevCache->setNextStatCache(statCache->takeNextStatCache()); 101 } 102 103 void FileManager::clearStatCaches() { 104 StatCache.reset(); 105 } 106 107 /// \brief Retrieve the directory that the given file name resides in. 108 /// Filename can point to either a real file or a virtual file. 109 static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr, 110 StringRef Filename, 111 bool CacheFailure) { 112 if (Filename.empty()) 113 return nullptr; 114 115 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1])) 116 return nullptr; // If Filename is a directory. 117 118 StringRef DirName = llvm::sys::path::parent_path(Filename); 119 // Use the current directory if file has no path component. 120 if (DirName.empty()) 121 DirName = "."; 122 123 return FileMgr.getDirectory(DirName, CacheFailure); 124 } 125 126 /// Add all ancestors of the given path (pointing to either a file or 127 /// a directory) as virtual directories. 128 void FileManager::addAncestorsAsVirtualDirs(StringRef Path) { 129 StringRef DirName = llvm::sys::path::parent_path(Path); 130 if (DirName.empty()) 131 return; 132 133 auto &NamedDirEnt = 134 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first; 135 136 // When caching a virtual directory, we always cache its ancestors 137 // at the same time. Therefore, if DirName is already in the cache, 138 // we don't need to recurse as its ancestors must also already be in 139 // the cache. 140 if (NamedDirEnt.second) 141 return; 142 143 // Add the virtual directory to the cache. 144 DirectoryEntry *UDE = new DirectoryEntry; 145 UDE->Name = NamedDirEnt.first().data(); 146 NamedDirEnt.second = UDE; 147 VirtualDirectoryEntries.push_back(UDE); 148 149 // Recursively add the other ancestors. 150 addAncestorsAsVirtualDirs(DirName); 151 } 152 153 const DirectoryEntry *FileManager::getDirectory(StringRef DirName, 154 bool CacheFailure) { 155 // stat doesn't like trailing separators except for root directory. 156 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'. 157 // (though it can strip '\\') 158 if (DirName.size() > 1 && 159 DirName != llvm::sys::path::root_path(DirName) && 160 llvm::sys::path::is_separator(DirName.back())) 161 DirName = DirName.substr(0, DirName.size()-1); 162 #ifdef LLVM_ON_WIN32 163 // Fixing a problem with "clang C:test.c" on Windows. 164 // Stat("C:") does not recognize "C:" as a valid directory 165 std::string DirNameStr; 166 if (DirName.size() > 1 && DirName.back() == ':' && 167 DirName.equals_lower(llvm::sys::path::root_name(DirName))) { 168 DirNameStr = DirName.str() + '.'; 169 DirName = DirNameStr; 170 } 171 #endif 172 173 ++NumDirLookups; 174 auto &NamedDirEnt = 175 *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first; 176 177 // See if there was already an entry in the map. Note that the map 178 // contains both virtual and real directories. 179 if (NamedDirEnt.second) 180 return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr 181 : NamedDirEnt.second; 182 183 ++NumDirCacheMisses; 184 185 // By default, initialize it to invalid. 186 NamedDirEnt.second = NON_EXISTENT_DIR; 187 188 // Get the null-terminated directory name as stored as the key of the 189 // SeenDirEntries map. 190 const char *InterndDirName = NamedDirEnt.first().data(); 191 192 // Check to see if the directory exists. 193 FileData Data; 194 if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) { 195 // There's no real directory at the given path. 196 if (!CacheFailure) 197 SeenDirEntries.erase(DirName); 198 return nullptr; 199 } 200 201 // It exists. See if we have already opened a directory with the 202 // same inode (this occurs on Unix-like systems when one dir is 203 // symlinked to another, for example) or the same path (on 204 // Windows). 205 DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID]; 206 207 NamedDirEnt.second = &UDE; 208 if (!UDE.getName()) { 209 // We don't have this directory yet, add it. We use the string 210 // key from the SeenDirEntries map as the string. 211 UDE.Name = InterndDirName; 212 } 213 214 return &UDE; 215 } 216 217 const FileEntry *FileManager::getFile(StringRef Filename, bool openFile, 218 bool CacheFailure) { 219 ++NumFileLookups; 220 221 // See if there is already an entry in the map. 222 auto &NamedFileEnt = 223 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first; 224 225 // See if there is already an entry in the map. 226 if (NamedFileEnt.second) 227 return NamedFileEnt.second == NON_EXISTENT_FILE ? nullptr 228 : NamedFileEnt.second; 229 230 ++NumFileCacheMisses; 231 232 // By default, initialize it to invalid. 233 NamedFileEnt.second = NON_EXISTENT_FILE; 234 235 // Get the null-terminated file name as stored as the key of the 236 // SeenFileEntries map. 237 const char *InterndFileName = NamedFileEnt.first().data(); 238 239 // Look up the directory for the file. When looking up something like 240 // sys/foo.h we'll discover all of the search directories that have a 'sys' 241 // subdirectory. This will let us avoid having to waste time on known-to-fail 242 // searches when we go to find sys/bar.h, because all the search directories 243 // without a 'sys' subdir will get a cached failure result. 244 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename, 245 CacheFailure); 246 if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist. 247 if (!CacheFailure) 248 SeenFileEntries.erase(Filename); 249 250 return nullptr; 251 } 252 253 // FIXME: Use the directory info to prune this, before doing the stat syscall. 254 // FIXME: This will reduce the # syscalls. 255 256 // Nope, there isn't. Check to see if the file exists. 257 std::unique_ptr<vfs::File> F; 258 FileData Data; 259 if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) { 260 // There's no real file at the given path. 261 if (!CacheFailure) 262 SeenFileEntries.erase(Filename); 263 264 return nullptr; 265 } 266 267 assert((openFile || !F) && "undesired open file"); 268 269 // It exists. See if we have already opened a file with the same inode. 270 // This occurs when one dir is symlinked to another, for example. 271 FileEntry &UFE = UniqueRealFiles[Data.UniqueID]; 272 273 NamedFileEnt.second = &UFE; 274 275 // If the name returned by getStatValue is different than Filename, re-intern 276 // the name. 277 if (Data.Name != Filename) { 278 auto &NamedFileEnt = 279 *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first; 280 if (!NamedFileEnt.second) 281 NamedFileEnt.second = &UFE; 282 else 283 assert(NamedFileEnt.second == &UFE && 284 "filename from getStatValue() refers to wrong file"); 285 InterndFileName = NamedFileEnt.first().data(); 286 } 287 288 if (UFE.isValid()) { // Already have an entry with this inode, return it. 289 290 // FIXME: this hack ensures that if we look up a file by a virtual path in 291 // the VFS that the getDir() will have the virtual path, even if we found 292 // the file by a 'real' path first. This is required in order to find a 293 // module's structure when its headers/module map are mapped in the VFS. 294 // We should remove this as soon as we can properly support a file having 295 // multiple names. 296 if (DirInfo != UFE.Dir && Data.IsVFSMapped) 297 UFE.Dir = DirInfo; 298 299 // Always update the name to use the last name by which a file was accessed. 300 // FIXME: Neither this nor always using the first name is correct; we want 301 // to switch towards a design where we return a FileName object that 302 // encapsulates both the name by which the file was accessed and the 303 // corresponding FileEntry. 304 UFE.Name = InterndFileName; 305 306 return &UFE; 307 } 308 309 // Otherwise, we don't have this file yet, add it. 310 UFE.Name = InterndFileName; 311 UFE.Size = Data.Size; 312 UFE.ModTime = Data.ModTime; 313 UFE.Dir = DirInfo; 314 UFE.UID = NextFileUID++; 315 UFE.UniqueID = Data.UniqueID; 316 UFE.IsNamedPipe = Data.IsNamedPipe; 317 UFE.InPCH = Data.InPCH; 318 UFE.File = std::move(F); 319 UFE.IsValid = true; 320 return &UFE; 321 } 322 323 const FileEntry * 324 FileManager::getVirtualFile(StringRef Filename, off_t Size, 325 time_t ModificationTime) { 326 ++NumFileLookups; 327 328 // See if there is already an entry in the map. 329 auto &NamedFileEnt = 330 *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first; 331 332 // See if there is already an entry in the map. 333 if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE) 334 return NamedFileEnt.second; 335 336 ++NumFileCacheMisses; 337 338 // By default, initialize it to invalid. 339 NamedFileEnt.second = NON_EXISTENT_FILE; 340 341 addAncestorsAsVirtualDirs(Filename); 342 FileEntry *UFE = nullptr; 343 344 // Now that all ancestors of Filename are in the cache, the 345 // following call is guaranteed to find the DirectoryEntry from the 346 // cache. 347 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename, 348 /*CacheFailure=*/true); 349 assert(DirInfo && 350 "The directory of a virtual file should already be in the cache."); 351 352 // Check to see if the file exists. If so, drop the virtual file 353 FileData Data; 354 const char *InterndFileName = NamedFileEnt.first().data(); 355 if (getStatValue(InterndFileName, Data, true, nullptr) == 0) { 356 Data.Size = Size; 357 Data.ModTime = ModificationTime; 358 UFE = &UniqueRealFiles[Data.UniqueID]; 359 360 NamedFileEnt.second = UFE; 361 362 // If we had already opened this file, close it now so we don't 363 // leak the descriptor. We're not going to use the file 364 // descriptor anyway, since this is a virtual file. 365 if (UFE->File) 366 UFE->closeFile(); 367 368 // If we already have an entry with this inode, return it. 369 if (UFE->isValid()) 370 return UFE; 371 372 UFE->UniqueID = Data.UniqueID; 373 UFE->IsNamedPipe = Data.IsNamedPipe; 374 UFE->InPCH = Data.InPCH; 375 } 376 377 if (!UFE) { 378 UFE = new FileEntry(); 379 VirtualFileEntries.push_back(UFE); 380 NamedFileEnt.second = UFE; 381 } 382 383 UFE->Name = InterndFileName; 384 UFE->Size = Size; 385 UFE->ModTime = ModificationTime; 386 UFE->Dir = DirInfo; 387 UFE->UID = NextFileUID++; 388 UFE->File.reset(); 389 return UFE; 390 } 391 392 bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const { 393 StringRef pathRef(path.data(), path.size()); 394 395 if (FileSystemOpts.WorkingDir.empty() 396 || llvm::sys::path::is_absolute(pathRef)) 397 return false; 398 399 SmallString<128> NewPath(FileSystemOpts.WorkingDir); 400 llvm::sys::path::append(NewPath, pathRef); 401 path = NewPath; 402 return true; 403 } 404 405 bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const { 406 bool Changed = FixupRelativePath(Path); 407 408 if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) { 409 llvm::sys::fs::make_absolute(Path); 410 Changed = true; 411 } 412 413 return Changed; 414 } 415 416 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 417 FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile, 418 bool ShouldCloseOpenFile) { 419 uint64_t FileSize = Entry->getSize(); 420 // If there's a high enough chance that the file have changed since we 421 // got its size, force a stat before opening it. 422 if (isVolatile) 423 FileSize = -1; 424 425 const char *Filename = Entry->getName(); 426 // If the file is already open, use the open file descriptor. 427 if (Entry->File) { 428 auto Result = 429 Entry->File->getBuffer(Filename, FileSize, 430 /*RequiresNullTerminator=*/true, isVolatile); 431 // FIXME: we need a set of APIs that can make guarantees about whether a 432 // FileEntry is open or not. 433 if (ShouldCloseOpenFile) 434 Entry->closeFile(); 435 return Result; 436 } 437 438 // Otherwise, open the file. 439 440 if (FileSystemOpts.WorkingDir.empty()) 441 return FS->getBufferForFile(Filename, FileSize, 442 /*RequiresNullTerminator=*/true, isVolatile); 443 444 SmallString<128> FilePath(Entry->getName()); 445 FixupRelativePath(FilePath); 446 return FS->getBufferForFile(FilePath, FileSize, 447 /*RequiresNullTerminator=*/true, isVolatile); 448 } 449 450 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 451 FileManager::getBufferForFile(StringRef Filename) { 452 if (FileSystemOpts.WorkingDir.empty()) 453 return FS->getBufferForFile(Filename); 454 455 SmallString<128> FilePath(Filename); 456 FixupRelativePath(FilePath); 457 return FS->getBufferForFile(FilePath.c_str()); 458 } 459 460 /// getStatValue - Get the 'stat' information for the specified path, 461 /// using the cache to accelerate it if possible. This returns true 462 /// if the path points to a virtual file or does not exist, or returns 463 /// false if it's an existent real file. If FileDescriptor is NULL, 464 /// do directory look-up instead of file look-up. 465 bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile, 466 std::unique_ptr<vfs::File> *F) { 467 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be 468 // absolute! 469 if (FileSystemOpts.WorkingDir.empty()) 470 return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS); 471 472 SmallString<128> FilePath(Path); 473 FixupRelativePath(FilePath); 474 475 return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F, 476 StatCache.get(), *FS); 477 } 478 479 bool FileManager::getNoncachedStatValue(StringRef Path, 480 vfs::Status &Result) { 481 SmallString<128> FilePath(Path); 482 FixupRelativePath(FilePath); 483 484 llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str()); 485 if (!S) 486 return true; 487 Result = *S; 488 return false; 489 } 490 491 void FileManager::invalidateCache(const FileEntry *Entry) { 492 assert(Entry && "Cannot invalidate a NULL FileEntry"); 493 494 SeenFileEntries.erase(Entry->getName()); 495 496 // FileEntry invalidation should not block future optimizations in the file 497 // caches. Possible alternatives are cache truncation (invalidate last N) or 498 // invalidation of the whole cache. 499 UniqueRealFiles.erase(Entry->getUniqueID()); 500 } 501 502 503 void FileManager::GetUniqueIDMapping( 504 SmallVectorImpl<const FileEntry *> &UIDToFiles) const { 505 UIDToFiles.clear(); 506 UIDToFiles.resize(NextFileUID); 507 508 // Map file entries 509 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator 510 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end(); 511 FE != FEEnd; ++FE) 512 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE) 513 UIDToFiles[FE->getValue()->getUID()] = FE->getValue(); 514 515 // Map virtual file entries 516 for (SmallVectorImpl<FileEntry *>::const_iterator 517 VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end(); 518 VFE != VFEEnd; ++VFE) 519 if (*VFE && *VFE != NON_EXISTENT_FILE) 520 UIDToFiles[(*VFE)->getUID()] = *VFE; 521 } 522 523 void FileManager::modifyFileEntry(FileEntry *File, 524 off_t Size, time_t ModificationTime) { 525 File->Size = Size; 526 File->ModTime = ModificationTime; 527 } 528 529 /// Remove '.' and '..' path components from the given absolute path. 530 /// \return \c true if any changes were made. 531 // FIXME: Move this to llvm::sys::path. 532 bool FileManager::removeDotPaths(SmallVectorImpl<char> &Path, bool RemoveDotDot) { 533 using namespace llvm::sys; 534 535 SmallVector<StringRef, 16> ComponentStack; 536 StringRef P(Path.data(), Path.size()); 537 538 // Skip the root path, then look for traversal in the components. 539 StringRef Rel = path::relative_path(P); 540 for (StringRef C : llvm::make_range(path::begin(Rel), path::end(Rel))) { 541 if (C == ".") 542 continue; 543 if (RemoveDotDot) { 544 if (C == "..") { 545 if (!ComponentStack.empty()) 546 ComponentStack.pop_back(); 547 continue; 548 } 549 } 550 ComponentStack.push_back(C); 551 } 552 553 SmallString<256> Buffer = path::root_path(P); 554 for (StringRef C : ComponentStack) 555 path::append(Buffer, C); 556 557 bool Changed = (Path != Buffer); 558 Path.swap(Buffer); 559 return Changed; 560 } 561 562 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) { 563 // FIXME: use llvm::sys::fs::canonical() when it gets implemented 564 llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known 565 = CanonicalDirNames.find(Dir); 566 if (Known != CanonicalDirNames.end()) 567 return Known->second; 568 569 StringRef CanonicalName(Dir->getName()); 570 571 #ifdef LLVM_ON_UNIX 572 char CanonicalNameBuf[PATH_MAX]; 573 if (realpath(Dir->getName(), CanonicalNameBuf)) 574 CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage); 575 #else 576 SmallString<256> CanonicalNameBuf(CanonicalName); 577 llvm::sys::fs::make_absolute(CanonicalNameBuf); 578 llvm::sys::path::native(CanonicalNameBuf); 579 // We've run into needing to remove '..' here in the wild though, so 580 // remove it. 581 // On Windows, symlinks are significantly less prevalent, so removing 582 // '..' is pretty safe. 583 // Ideally we'd have an equivalent of `realpath` and could implement 584 // sys::fs::canonical across all the platforms. 585 removeDotPaths(CanonicalNameBuf, /*RemoveDotDot*/true); 586 CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage); 587 #endif 588 589 CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName)); 590 return CanonicalName; 591 } 592 593 void FileManager::PrintStats() const { 594 llvm::errs() << "\n*** File Manager Stats:\n"; 595 llvm::errs() << UniqueRealFiles.size() << " real files found, " 596 << UniqueRealDirs.size() << " real dirs found.\n"; 597 llvm::errs() << VirtualFileEntries.size() << " virtual files found, " 598 << VirtualDirectoryEntries.size() << " virtual dirs found.\n"; 599 llvm::errs() << NumDirLookups << " dir lookups, " 600 << NumDirCacheMisses << " dir cache misses.\n"; 601 llvm::errs() << NumFileLookups << " file lookups, " 602 << NumFileCacheMisses << " file cache misses.\n"; 603 604 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; 605 } 606 607 // Virtual destructors for abstract base classes that need live in Basic. 608 PCHContainerWriter::~PCHContainerWriter() {} 609 PCHContainerReader::~PCHContainerReader() {} 610