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