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