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