1 //===--- FileManager.cpp - File System Probing and Caching ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the FileManager interface. 10 // 11 //===----------------------------------------------------------------------===// 12 // 13 // TODO: This should index all interesting directories with dirent calls. 14 // getdirentries ? 15 // opendir/readdir_r/closedir ? 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "clang/Basic/FileManager.h" 20 #include "clang/Basic/FileSystemStatCache.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/SmallString.h" 23 #include "llvm/ADT/Statistic.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 <algorithm> 30 #include <cassert> 31 #include <climits> 32 #include <cstdint> 33 #include <cstdlib> 34 #include <optional> 35 #include <string> 36 #include <utility> 37 38 using namespace clang; 39 40 #define DEBUG_TYPE "file-search" 41 42 //===----------------------------------------------------------------------===// 43 // Common logic. 44 //===----------------------------------------------------------------------===// 45 46 FileManager::FileManager(const FileSystemOptions &FSO, 47 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) 48 : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64), 49 SeenFileEntries(64), NextFileUID(0) { 50 // If the caller doesn't provide a virtual file system, just grab the real 51 // file system. 52 if (!this->FS) 53 this->FS = llvm::vfs::getRealFileSystem(); 54 } 55 56 FileManager::~FileManager() = default; 57 58 void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) { 59 assert(statCache && "No stat cache provided?"); 60 StatCache = std::move(statCache); 61 } 62 63 void FileManager::clearStatCache() { StatCache.reset(); } 64 65 /// Retrieve the directory that the given file name resides in. 66 /// Filename can point to either a real file or a virtual file. 67 static llvm::Expected<DirectoryEntryRef> 68 getDirectoryFromFile(FileManager &FileMgr, StringRef Filename, 69 bool CacheFailure) { 70 if (Filename.empty()) 71 return llvm::errorCodeToError( 72 make_error_code(std::errc::no_such_file_or_directory)); 73 74 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1])) 75 return llvm::errorCodeToError(make_error_code(std::errc::is_a_directory)); 76 77 StringRef DirName = llvm::sys::path::parent_path(Filename); 78 // Use the current directory if file has no path component. 79 if (DirName.empty()) 80 DirName = "."; 81 82 return FileMgr.getDirectoryRef(DirName, CacheFailure); 83 } 84 85 DirectoryEntry *&FileManager::getRealDirEntry(const llvm::vfs::Status &Status) { 86 assert(Status.isDirectory() && "The directory should exist!"); 87 // See if we have already opened a directory with the 88 // same inode (this occurs on Unix-like systems when one dir is 89 // symlinked to another, for example) or the same path (on 90 // Windows). 91 DirectoryEntry *&UDE = UniqueRealDirs[Status.getUniqueID()]; 92 93 if (!UDE) { 94 // We don't have this directory yet, add it. We use the string 95 // key from the SeenDirEntries map as the string. 96 UDE = new (DirsAlloc.Allocate()) DirectoryEntry(); 97 } 98 return UDE; 99 } 100 101 /// Add all ancestors of the given path (pointing to either a file or 102 /// a directory) as virtual directories. 103 void FileManager::addAncestorsAsVirtualDirs(StringRef Path) { 104 StringRef DirName = llvm::sys::path::parent_path(Path); 105 if (DirName.empty()) 106 DirName = "."; 107 108 auto &NamedDirEnt = *SeenDirEntries.insert( 109 {DirName, std::errc::no_such_file_or_directory}).first; 110 111 // When caching a virtual directory, we always cache its ancestors 112 // at the same time. Therefore, if DirName is already in the cache, 113 // we don't need to recurse as its ancestors must also already be in 114 // the cache (or it's a known non-virtual directory). 115 if (NamedDirEnt.second) 116 return; 117 118 // Check to see if the directory exists. 119 llvm::vfs::Status Status; 120 auto statError = 121 getStatValue(DirName, Status, false, nullptr /*directory lookup*/); 122 if (statError) { 123 // There's no real directory at the given path. 124 // Add the virtual directory to the cache. 125 auto *UDE = new (DirsAlloc.Allocate()) DirectoryEntry(); 126 NamedDirEnt.second = *UDE; 127 VirtualDirectoryEntries.push_back(UDE); 128 } else { 129 // There is the real directory 130 DirectoryEntry *&UDE = getRealDirEntry(Status); 131 NamedDirEnt.second = *UDE; 132 } 133 134 // Recursively add the other ancestors. 135 addAncestorsAsVirtualDirs(DirName); 136 } 137 138 llvm::Expected<DirectoryEntryRef> 139 FileManager::getDirectoryRef(StringRef DirName, bool CacheFailure) { 140 // stat doesn't like trailing separators except for root directory. 141 // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'. 142 // (though it can strip '\\') 143 if (DirName.size() > 1 && 144 DirName != llvm::sys::path::root_path(DirName) && 145 llvm::sys::path::is_separator(DirName.back())) 146 DirName = DirName.substr(0, DirName.size()-1); 147 std::optional<std::string> DirNameStr; 148 if (is_style_windows(llvm::sys::path::Style::native)) { 149 // Fixing a problem with "clang C:test.c" on Windows. 150 // Stat("C:") does not recognize "C:" as a valid directory 151 if (DirName.size() > 1 && DirName.back() == ':' && 152 DirName.equals_insensitive(llvm::sys::path::root_name(DirName))) { 153 DirNameStr = DirName.str() + '.'; 154 DirName = *DirNameStr; 155 } 156 } 157 158 ++NumDirLookups; 159 160 // See if there was already an entry in the map. Note that the map 161 // contains both virtual and real directories. 162 auto SeenDirInsertResult = 163 SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory}); 164 if (!SeenDirInsertResult.second) { 165 if (SeenDirInsertResult.first->second) 166 return DirectoryEntryRef(*SeenDirInsertResult.first); 167 return llvm::errorCodeToError(SeenDirInsertResult.first->second.getError()); 168 } 169 170 // We've not seen this before. Fill it in. 171 ++NumDirCacheMisses; 172 auto &NamedDirEnt = *SeenDirInsertResult.first; 173 assert(!NamedDirEnt.second && "should be newly-created"); 174 175 // Get the null-terminated directory name as stored as the key of the 176 // SeenDirEntries map. 177 StringRef InterndDirName = NamedDirEnt.first(); 178 179 // Check to see if the directory exists. 180 llvm::vfs::Status Status; 181 auto statError = getStatValue(InterndDirName, Status, false, 182 nullptr /*directory lookup*/); 183 if (statError) { 184 // There's no real directory at the given path. 185 if (CacheFailure) 186 NamedDirEnt.second = statError; 187 else 188 SeenDirEntries.erase(DirName); 189 return llvm::errorCodeToError(statError); 190 } 191 192 // It exists. 193 DirectoryEntry *&UDE = getRealDirEntry(Status); 194 NamedDirEnt.second = *UDE; 195 196 return DirectoryEntryRef(NamedDirEnt); 197 } 198 199 llvm::ErrorOr<const DirectoryEntry *> 200 FileManager::getDirectory(StringRef DirName, bool CacheFailure) { 201 auto Result = getDirectoryRef(DirName, CacheFailure); 202 if (Result) 203 return &Result->getDirEntry(); 204 return llvm::errorToErrorCode(Result.takeError()); 205 } 206 207 llvm::ErrorOr<const FileEntry *> 208 FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) { 209 auto Result = getFileRef(Filename, openFile, CacheFailure); 210 if (Result) 211 return &Result->getFileEntry(); 212 return llvm::errorToErrorCode(Result.takeError()); 213 } 214 215 llvm::Expected<FileEntryRef> FileManager::getFileRef(StringRef Filename, 216 bool openFile, 217 bool CacheFailure, 218 bool IsText) { 219 ++NumFileLookups; 220 221 // See if there is already an entry in the map. 222 auto SeenFileInsertResult = 223 SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory}); 224 if (!SeenFileInsertResult.second) { 225 if (!SeenFileInsertResult.first->second) 226 return llvm::errorCodeToError( 227 SeenFileInsertResult.first->second.getError()); 228 return FileEntryRef(*SeenFileInsertResult.first); 229 } 230 231 // We've not seen this before. Fill it in. 232 ++NumFileCacheMisses; 233 auto *NamedFileEnt = &*SeenFileInsertResult.first; 234 assert(!NamedFileEnt->second && "should be newly-created"); 235 236 // Get the null-terminated file name as stored as the key of the 237 // SeenFileEntries map. 238 StringRef InterndFileName = NamedFileEnt->first(); 239 240 // Look up the directory for the file. When looking up something like 241 // sys/foo.h we'll discover all of the search directories that have a 'sys' 242 // subdirectory. This will let us avoid having to waste time on known-to-fail 243 // searches when we go to find sys/bar.h, because all the search directories 244 // without a 'sys' subdir will get a cached failure result. 245 auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure); 246 if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist. 247 std::error_code Err = errorToErrorCode(DirInfoOrErr.takeError()); 248 if (CacheFailure) 249 NamedFileEnt->second = Err; 250 else 251 SeenFileEntries.erase(Filename); 252 253 return llvm::errorCodeToError(Err); 254 } 255 DirectoryEntryRef DirInfo = *DirInfoOrErr; 256 257 // FIXME: Use the directory info to prune this, before doing the stat syscall. 258 // FIXME: This will reduce the # syscalls. 259 260 // Check to see if the file exists. 261 std::unique_ptr<llvm::vfs::File> F; 262 llvm::vfs::Status Status; 263 auto statError = getStatValue(InterndFileName, Status, true, 264 openFile ? &F : nullptr, IsText); 265 if (statError) { 266 // There's no real file at the given path. 267 if (CacheFailure) 268 NamedFileEnt->second = statError; 269 else 270 SeenFileEntries.erase(Filename); 271 272 return llvm::errorCodeToError(statError); 273 } 274 275 assert((openFile || !F) && "undesired open file"); 276 277 // It exists. See if we have already opened a file with the same inode. 278 // This occurs when one dir is symlinked to another, for example. 279 FileEntry *&UFE = UniqueRealFiles[Status.getUniqueID()]; 280 bool ReusingEntry = UFE != nullptr; 281 if (!UFE) 282 UFE = new (FilesAlloc.Allocate()) FileEntry(); 283 284 if (!Status.ExposesExternalVFSPath || Status.getName() == Filename) { 285 // Use the requested name. Set the FileEntry. 286 NamedFileEnt->second = FileEntryRef::MapValue(*UFE, DirInfo); 287 } else { 288 // Name mismatch. We need a redirect. First grab the actual entry we want 289 // to return. 290 // 291 // This redirection logic intentionally leaks the external name of a 292 // redirected file that uses 'use-external-name' in \a 293 // vfs::RedirectionFileSystem. This allows clang to report the external 294 // name to users (in diagnostics) and to tools that don't have access to 295 // the VFS (in debug info and dependency '.d' files). 296 // 297 // FIXME: This is pretty complex and has some very complicated interactions 298 // with the rest of clang. It's also inconsistent with how "real" 299 // filesystems behave and confuses parts of clang expect to see the 300 // name-as-accessed on the \a FileEntryRef. 301 // 302 // A potential plan to remove this is as follows - 303 // - Update callers such as `HeaderSearch::findUsableModuleForHeader()` 304 // to explicitly use the `getNameAsRequested()` rather than just using 305 // `getName()`. 306 // - Add a `FileManager::getExternalPath` API for explicitly getting the 307 // remapped external filename when there is one available. Adopt it in 308 // callers like diagnostics/deps reporting instead of calling 309 // `getName()` directly. 310 // - Switch the meaning of `FileEntryRef::getName()` to get the requested 311 // name, not the external name. Once that sticks, revert callers that 312 // want the requested name back to calling `getName()`. 313 // - Update the VFS to always return the requested name. This could also 314 // return the external name, or just have an API to request it 315 // lazily. The latter has the benefit of making accesses of the 316 // external path easily tracked, but may also require extra work than 317 // just returning up front. 318 // - (Optionally) Add an API to VFS to get the external filename lazily 319 // and update `FileManager::getExternalPath()` to use it instead. This 320 // has the benefit of making such accesses easily tracked, though isn't 321 // necessarily required (and could cause extra work than just adding to 322 // eg. `vfs::Status` up front). 323 auto &Redirection = 324 *SeenFileEntries 325 .insert({Status.getName(), FileEntryRef::MapValue(*UFE, DirInfo)}) 326 .first; 327 assert(isa<FileEntry *>(Redirection.second->V) && 328 "filename redirected to a non-canonical filename?"); 329 assert(cast<FileEntry *>(Redirection.second->V) == UFE && 330 "filename from getStatValue() refers to wrong file"); 331 332 // Cache the redirection in the previously-inserted entry, still available 333 // in the tentative return value. 334 NamedFileEnt->second = FileEntryRef::MapValue(Redirection, DirInfo); 335 } 336 337 FileEntryRef ReturnedRef(*NamedFileEnt); 338 if (ReusingEntry) { // Already have an entry with this inode, return it. 339 return ReturnedRef; 340 } 341 342 // Otherwise, we don't have this file yet, add it. 343 UFE->Size = Status.getSize(); 344 UFE->ModTime = llvm::sys::toTimeT(Status.getLastModificationTime()); 345 UFE->Dir = &DirInfo.getDirEntry(); 346 UFE->UID = NextFileUID++; 347 UFE->UniqueID = Status.getUniqueID(); 348 UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file; 349 UFE->File = std::move(F); 350 351 if (UFE->File) { 352 if (auto PathName = UFE->File->getName()) 353 fillRealPathName(UFE, *PathName); 354 } else if (!openFile) { 355 // We should still fill the path even if we aren't opening the file. 356 fillRealPathName(UFE, InterndFileName); 357 } 358 return ReturnedRef; 359 } 360 361 llvm::Expected<FileEntryRef> FileManager::getSTDIN() { 362 // Only read stdin once. 363 if (STDIN) 364 return *STDIN; 365 366 std::unique_ptr<llvm::MemoryBuffer> Content; 367 if (auto ContentOrError = llvm::MemoryBuffer::getSTDIN()) 368 Content = std::move(*ContentOrError); 369 else 370 return llvm::errorCodeToError(ContentOrError.getError()); 371 372 STDIN = getVirtualFileRef(Content->getBufferIdentifier(), 373 Content->getBufferSize(), 0); 374 FileEntry &FE = const_cast<FileEntry &>(STDIN->getFileEntry()); 375 FE.Content = std::move(Content); 376 FE.IsNamedPipe = true; 377 return *STDIN; 378 } 379 380 void FileManager::trackVFSUsage(bool Active) { 381 FS->visit([Active](llvm::vfs::FileSystem &FileSys) { 382 if (auto *RFS = dyn_cast<llvm::vfs::RedirectingFileSystem>(&FileSys)) 383 RFS->setUsageTrackingActive(Active); 384 }); 385 } 386 387 const FileEntry *FileManager::getVirtualFile(StringRef Filename, off_t Size, 388 time_t ModificationTime) { 389 return &getVirtualFileRef(Filename, Size, ModificationTime).getFileEntry(); 390 } 391 392 FileEntryRef FileManager::getVirtualFileRef(StringRef Filename, off_t Size, 393 time_t ModificationTime) { 394 ++NumFileLookups; 395 396 // See if there is already an entry in the map for an existing file. 397 auto &NamedFileEnt = *SeenFileEntries.insert( 398 {Filename, std::errc::no_such_file_or_directory}).first; 399 if (NamedFileEnt.second) { 400 FileEntryRef::MapValue Value = *NamedFileEnt.second; 401 if (LLVM_LIKELY(isa<FileEntry *>(Value.V))) 402 return FileEntryRef(NamedFileEnt); 403 return FileEntryRef(*cast<const FileEntryRef::MapEntry *>(Value.V)); 404 } 405 406 // We've not seen this before, or the file is cached as non-existent. 407 ++NumFileCacheMisses; 408 addAncestorsAsVirtualDirs(Filename); 409 FileEntry *UFE = nullptr; 410 411 // Now that all ancestors of Filename are in the cache, the 412 // following call is guaranteed to find the DirectoryEntry from the 413 // cache. A virtual file can also have an empty filename, that could come 414 // from a source location preprocessor directive with an empty filename as 415 // an example, so we need to pretend it has a name to ensure a valid directory 416 // entry can be returned. 417 auto DirInfo = expectedToOptional(getDirectoryFromFile( 418 *this, Filename.empty() ? "." : Filename, /*CacheFailure=*/true)); 419 assert(DirInfo && 420 "The directory of a virtual file should already be in the cache."); 421 422 // Check to see if the file exists. If so, drop the virtual file 423 llvm::vfs::Status Status; 424 const char *InterndFileName = NamedFileEnt.first().data(); 425 if (!getStatValue(InterndFileName, Status, true, nullptr)) { 426 Status = llvm::vfs::Status( 427 Status.getName(), Status.getUniqueID(), 428 llvm::sys::toTimePoint(ModificationTime), 429 Status.getUser(), Status.getGroup(), Size, 430 Status.getType(), Status.getPermissions()); 431 432 auto &RealFE = UniqueRealFiles[Status.getUniqueID()]; 433 if (RealFE) { 434 // If we had already opened this file, close it now so we don't 435 // leak the descriptor. We're not going to use the file 436 // descriptor anyway, since this is a virtual file. 437 if (RealFE->File) 438 RealFE->closeFile(); 439 // If we already have an entry with this inode, return it. 440 // 441 // FIXME: Surely this should add a reference by the new name, and return 442 // it instead... 443 NamedFileEnt.second = FileEntryRef::MapValue(*RealFE, *DirInfo); 444 return FileEntryRef(NamedFileEnt); 445 } 446 // File exists, but no entry - create it. 447 RealFE = new (FilesAlloc.Allocate()) FileEntry(); 448 RealFE->UniqueID = Status.getUniqueID(); 449 RealFE->IsNamedPipe = 450 Status.getType() == llvm::sys::fs::file_type::fifo_file; 451 fillRealPathName(RealFE, Status.getName()); 452 453 UFE = RealFE; 454 } else { 455 // File does not exist, create a virtual entry. 456 UFE = new (FilesAlloc.Allocate()) FileEntry(); 457 VirtualFileEntries.push_back(UFE); 458 } 459 460 NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo); 461 UFE->Size = Size; 462 UFE->ModTime = ModificationTime; 463 UFE->Dir = &DirInfo->getDirEntry(); 464 UFE->UID = NextFileUID++; 465 UFE->File.reset(); 466 return FileEntryRef(NamedFileEnt); 467 } 468 469 OptionalFileEntryRef FileManager::getBypassFile(FileEntryRef VF) { 470 // Stat of the file and return nullptr if it doesn't exist. 471 llvm::vfs::Status Status; 472 if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr)) 473 return std::nullopt; 474 475 if (!SeenBypassFileEntries) 476 SeenBypassFileEntries = std::make_unique< 477 llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>(); 478 479 // If we've already bypassed just use the existing one. 480 auto Insertion = SeenBypassFileEntries->insert( 481 {VF.getName(), std::errc::no_such_file_or_directory}); 482 if (!Insertion.second) 483 return FileEntryRef(*Insertion.first); 484 485 // Fill in the new entry from the stat. 486 FileEntry *BFE = new (FilesAlloc.Allocate()) FileEntry(); 487 BypassFileEntries.push_back(BFE); 488 Insertion.first->second = FileEntryRef::MapValue(*BFE, VF.getDir()); 489 BFE->Size = Status.getSize(); 490 BFE->Dir = VF.getFileEntry().Dir; 491 BFE->ModTime = llvm::sys::toTimeT(Status.getLastModificationTime()); 492 BFE->UID = NextFileUID++; 493 494 // Save the entry in the bypass table and return. 495 return FileEntryRef(*Insertion.first); 496 } 497 498 bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const { 499 StringRef pathRef(path.data(), path.size()); 500 501 if (FileSystemOpts.WorkingDir.empty() 502 || llvm::sys::path::is_absolute(pathRef)) 503 return false; 504 505 SmallString<128> NewPath(FileSystemOpts.WorkingDir); 506 llvm::sys::path::append(NewPath, pathRef); 507 path = NewPath; 508 return true; 509 } 510 511 bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const { 512 bool Changed = FixupRelativePath(Path); 513 514 if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) { 515 FS->makeAbsolute(Path); 516 Changed = true; 517 } 518 519 return Changed; 520 } 521 522 void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) { 523 llvm::SmallString<128> AbsPath(FileName); 524 // This is not the same as `VFS::getRealPath()`, which resolves symlinks 525 // but can be very expensive on real file systems. 526 // FIXME: the semantic of RealPathName is unclear, and the name might be 527 // misleading. We need to clean up the interface here. 528 makeAbsolutePath(AbsPath); 529 llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true); 530 UFE->RealPathName = std::string(AbsPath); 531 } 532 533 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 534 FileManager::getBufferForFile(FileEntryRef FE, bool isVolatile, 535 bool RequiresNullTerminator, 536 std::optional<int64_t> MaybeLimit, bool IsText) { 537 const FileEntry *Entry = &FE.getFileEntry(); 538 // If the content is living on the file entry, return a reference to it. 539 if (Entry->Content) 540 return llvm::MemoryBuffer::getMemBuffer(Entry->Content->getMemBufferRef()); 541 542 uint64_t FileSize = Entry->getSize(); 543 544 if (MaybeLimit) 545 FileSize = *MaybeLimit; 546 547 // If there's a high enough chance that the file have changed since we 548 // got its size, force a stat before opening it. 549 if (isVolatile || Entry->isNamedPipe()) 550 FileSize = -1; 551 552 StringRef Filename = FE.getName(); 553 // If the file is already open, use the open file descriptor. 554 if (Entry->File) { 555 auto Result = Entry->File->getBuffer(Filename, FileSize, 556 RequiresNullTerminator, isVolatile); 557 Entry->closeFile(); 558 return Result; 559 } 560 561 // Otherwise, open the file. 562 return getBufferForFileImpl(Filename, FileSize, isVolatile, 563 RequiresNullTerminator, IsText); 564 } 565 566 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 567 FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize, 568 bool isVolatile, bool RequiresNullTerminator, 569 bool IsText) const { 570 if (FileSystemOpts.WorkingDir.empty()) 571 return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator, 572 isVolatile, IsText); 573 574 SmallString<128> FilePath(Filename); 575 FixupRelativePath(FilePath); 576 return FS->getBufferForFile(FilePath, FileSize, RequiresNullTerminator, 577 isVolatile, IsText); 578 } 579 580 /// getStatValue - Get the 'stat' information for the specified path, 581 /// using the cache to accelerate it if possible. This returns true 582 /// if the path points to a virtual file or does not exist, or returns 583 /// false if it's an existent real file. If FileDescriptor is NULL, 584 /// do directory look-up instead of file look-up. 585 std::error_code FileManager::getStatValue(StringRef Path, 586 llvm::vfs::Status &Status, 587 bool isFile, 588 std::unique_ptr<llvm::vfs::File> *F, 589 bool IsText) { 590 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be 591 // absolute! 592 if (FileSystemOpts.WorkingDir.empty()) 593 return FileSystemStatCache::get(Path, Status, isFile, F, StatCache.get(), 594 *FS, IsText); 595 596 SmallString<128> FilePath(Path); 597 FixupRelativePath(FilePath); 598 599 return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F, 600 StatCache.get(), *FS, IsText); 601 } 602 603 std::error_code 604 FileManager::getNoncachedStatValue(StringRef Path, 605 llvm::vfs::Status &Result) { 606 SmallString<128> FilePath(Path); 607 FixupRelativePath(FilePath); 608 609 llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str()); 610 if (!S) 611 return S.getError(); 612 Result = *S; 613 return std::error_code(); 614 } 615 616 void FileManager::GetUniqueIDMapping( 617 SmallVectorImpl<OptionalFileEntryRef> &UIDToFiles) const { 618 UIDToFiles.clear(); 619 UIDToFiles.resize(NextFileUID); 620 621 for (const auto &Entry : SeenFileEntries) { 622 // Only return files that exist and are not redirected. 623 if (!Entry.getValue() || !isa<FileEntry *>(Entry.getValue()->V)) 624 continue; 625 FileEntryRef FE(Entry); 626 // Add this file if it's the first one with the UID, or if its name is 627 // better than the existing one. 628 OptionalFileEntryRef &ExistingFE = UIDToFiles[FE.getUID()]; 629 if (!ExistingFE || FE.getName() < ExistingFE->getName()) 630 ExistingFE = FE; 631 } 632 } 633 634 StringRef FileManager::getCanonicalName(DirectoryEntryRef Dir) { 635 return getCanonicalName(Dir, Dir.getName()); 636 } 637 638 StringRef FileManager::getCanonicalName(FileEntryRef File) { 639 return getCanonicalName(File, File.getName()); 640 } 641 642 StringRef FileManager::getCanonicalName(const void *Entry, StringRef Name) { 643 llvm::DenseMap<const void *, llvm::StringRef>::iterator Known = 644 CanonicalNames.find(Entry); 645 if (Known != CanonicalNames.end()) 646 return Known->second; 647 648 // Name comes from FileEntry/DirectoryEntry::getName(), so it is safe to 649 // store it in the DenseMap below. 650 StringRef CanonicalName(Name); 651 652 SmallString<256> AbsPathBuf; 653 SmallString<256> RealPathBuf; 654 if (!FS->getRealPath(Name, RealPathBuf)) { 655 if (is_style_windows(llvm::sys::path::Style::native)) { 656 // For Windows paths, only use the real path if it doesn't resolve 657 // a substitute drive, as those are used to avoid MAX_PATH issues. 658 AbsPathBuf = Name; 659 if (!FS->makeAbsolute(AbsPathBuf)) { 660 if (llvm::sys::path::root_name(RealPathBuf) == 661 llvm::sys::path::root_name(AbsPathBuf)) { 662 CanonicalName = RealPathBuf.str().copy(CanonicalNameStorage); 663 } else { 664 // Fallback to using the absolute path. 665 // Simplifying /../ is semantically valid on Windows even in the 666 // presence of symbolic links. 667 llvm::sys::path::remove_dots(AbsPathBuf, /*remove_dot_dot=*/true); 668 CanonicalName = AbsPathBuf.str().copy(CanonicalNameStorage); 669 } 670 } 671 } else { 672 CanonicalName = RealPathBuf.str().copy(CanonicalNameStorage); 673 } 674 } 675 676 CanonicalNames.insert({Entry, CanonicalName}); 677 return CanonicalName; 678 } 679 680 void FileManager::AddStats(const FileManager &Other) { 681 assert(&Other != this && "Collecting stats into the same FileManager"); 682 NumDirLookups += Other.NumDirLookups; 683 NumFileLookups += Other.NumFileLookups; 684 NumDirCacheMisses += Other.NumDirCacheMisses; 685 NumFileCacheMisses += Other.NumFileCacheMisses; 686 } 687 688 void FileManager::PrintStats() const { 689 llvm::errs() << "\n*** File Manager Stats:\n"; 690 llvm::errs() << UniqueRealFiles.size() << " real files found, " 691 << UniqueRealDirs.size() << " real dirs found.\n"; 692 llvm::errs() << VirtualFileEntries.size() << " virtual files found, " 693 << VirtualDirectoryEntries.size() << " virtual dirs found.\n"; 694 llvm::errs() << NumDirLookups << " dir lookups, " 695 << NumDirCacheMisses << " dir cache misses.\n"; 696 llvm::errs() << NumFileLookups << " file lookups, " 697 << NumFileCacheMisses << " file cache misses.\n"; 698 699 getVirtualFileSystem().visit([](llvm::vfs::FileSystem &VFS) { 700 if (auto *T = dyn_cast_or_null<llvm::vfs::TracingFileSystem>(&VFS)) 701 llvm::errs() << "\n*** Virtual File System Stats:\n" 702 << T->NumStatusCalls << " status() calls\n" 703 << T->NumOpenFileForReadCalls << " openFileForRead() calls\n" 704 << T->NumDirBeginCalls << " dir_begin() calls\n" 705 << T->NumGetRealPathCalls << " getRealPath() calls\n" 706 << T->NumExistsCalls << " exists() calls\n" 707 << T->NumIsLocalCalls << " isLocal() calls\n"; 708 }); 709 710 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; 711 } 712