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.ExposesExternalVFSPath || Status.getName() == Filename) { 278 // Use the requested name. 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 complex and has some very complicated interactions 291 // with the rest of clang. It's also inconsistent with how "real" 292 // filesystems behave and confuses parts of clang expect to see the 293 // name-as-accessed on the \a FileEntryRef. 294 // 295 // A potential plan to remove this is as follows - 296 // - Update callers such as `HeaderSearch::findUsableModuleForHeader()` 297 // to explicitly use the `getNameAsRequested()` rather than just using 298 // `getName()`. 299 // - Add a `FileManager::getExternalPath` API for explicitly getting the 300 // remapped external filename when there is one available. Adopt it in 301 // callers like diagnostics/deps reporting instead of calling 302 // `getName()` directly. 303 // - Switch the meaning of `FileEntryRef::getName()` to get the requested 304 // name, not the external name. Once that sticks, revert callers that 305 // want the requested name back to calling `getName()`. 306 // - Update the VFS to always return the requested name. This could also 307 // return the external name, or just have an API to request it 308 // lazily. The latter has the benefit of making accesses of the 309 // external path easily tracked, but may also require extra work than 310 // just returning up front. 311 // - (Optionally) Add an API to VFS to get the external filename lazily 312 // and update `FileManager::getExternalPath()` to use it instead. This 313 // has the benefit of making such accesses easily tracked, though isn't 314 // necessarily required (and could cause extra work than just adding to 315 // eg. `vfs::Status` up front). 316 auto &Redirection = 317 *SeenFileEntries 318 .insert({Status.getName(), FileEntryRef::MapValue(*UFE, DirInfo)}) 319 .first; 320 assert(Redirection.second->V.is<FileEntry *>() && 321 "filename redirected to a non-canonical filename?"); 322 assert(Redirection.second->V.get<FileEntry *>() == UFE && 323 "filename from getStatValue() refers to wrong file"); 324 325 // Cache the redirection in the previously-inserted entry, still available 326 // in the tentative return value. 327 NamedFileEnt->second = FileEntryRef::MapValue(Redirection); 328 } 329 330 FileEntryRef ReturnedRef(*NamedFileEnt); 331 if (ReusingEntry) { // Already have an entry with this inode, return it. 332 333 // FIXME: This hack ensures that `getDir()` will use the path that was 334 // used to lookup this file, even if we found a file by different path 335 // first. This is required in order to find a module's structure when its 336 // headers/module map are mapped in the VFS. 337 // 338 // See above for how this will eventually be removed. `IsVFSMapped` 339 // *cannot* be narrowed to `ExposesExternalVFSPath` as crash reproducers 340 // also depend on this logic and they have `use-external-paths: false`. 341 if (&DirInfo.getDirEntry() != UFE->Dir && Status.IsVFSMapped) 342 UFE->Dir = &DirInfo.getDirEntry(); 343 344 // Always update LastRef to the last name by which a file was accessed. 345 // FIXME: Neither this nor always using the first reference is correct; we 346 // want to switch towards a design where we return a FileName object that 347 // encapsulates both the name by which the file was accessed and the 348 // corresponding FileEntry. 349 // FIXME: LastRef should be removed from FileEntry once all clients adopt 350 // FileEntryRef. 351 UFE->LastRef = ReturnedRef; 352 353 return ReturnedRef; 354 } 355 356 // Otherwise, we don't have this file yet, add it. 357 UFE->LastRef = ReturnedRef; 358 UFE->Size = Status.getSize(); 359 UFE->ModTime = llvm::sys::toTimeT(Status.getLastModificationTime()); 360 UFE->Dir = &DirInfo.getDirEntry(); 361 UFE->UID = NextFileUID++; 362 UFE->UniqueID = Status.getUniqueID(); 363 UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file; 364 UFE->File = std::move(F); 365 366 if (UFE->File) { 367 if (auto PathName = UFE->File->getName()) 368 fillRealPathName(UFE, *PathName); 369 } else if (!openFile) { 370 // We should still fill the path even if we aren't opening the file. 371 fillRealPathName(UFE, InterndFileName); 372 } 373 return ReturnedRef; 374 } 375 376 llvm::Expected<FileEntryRef> FileManager::getSTDIN() { 377 // Only read stdin once. 378 if (STDIN) 379 return *STDIN; 380 381 std::unique_ptr<llvm::MemoryBuffer> Content; 382 if (auto ContentOrError = llvm::MemoryBuffer::getSTDIN()) 383 Content = std::move(*ContentOrError); 384 else 385 return llvm::errorCodeToError(ContentOrError.getError()); 386 387 STDIN = getVirtualFileRef(Content->getBufferIdentifier(), 388 Content->getBufferSize(), 0); 389 FileEntry &FE = const_cast<FileEntry &>(STDIN->getFileEntry()); 390 FE.Content = std::move(Content); 391 FE.IsNamedPipe = true; 392 return *STDIN; 393 } 394 395 const FileEntry *FileManager::getVirtualFile(StringRef Filename, off_t Size, 396 time_t ModificationTime) { 397 return &getVirtualFileRef(Filename, Size, ModificationTime).getFileEntry(); 398 } 399 400 FileEntryRef FileManager::getVirtualFileRef(StringRef Filename, off_t Size, 401 time_t ModificationTime) { 402 ++NumFileLookups; 403 404 // See if there is already an entry in the map for an existing file. 405 auto &NamedFileEnt = *SeenFileEntries.insert( 406 {Filename, std::errc::no_such_file_or_directory}).first; 407 if (NamedFileEnt.second) { 408 FileEntryRef::MapValue Value = *NamedFileEnt.second; 409 if (LLVM_LIKELY(Value.V.is<FileEntry *>())) 410 return FileEntryRef(NamedFileEnt); 411 return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>( 412 Value.V.get<const void *>())); 413 } 414 415 // We've not seen this before, or the file is cached as non-existent. 416 ++NumFileCacheMisses; 417 addAncestorsAsVirtualDirs(Filename); 418 FileEntry *UFE = nullptr; 419 420 // Now that all ancestors of Filename are in the cache, the 421 // following call is guaranteed to find the DirectoryEntry from the 422 // cache. A virtual file can also have an empty filename, that could come 423 // from a source location preprocessor directive with an empty filename as 424 // an example, so we need to pretend it has a name to ensure a valid directory 425 // entry can be returned. 426 auto DirInfo = expectedToOptional(getDirectoryFromFile( 427 *this, Filename.empty() ? "." : Filename, /*CacheFailure=*/true)); 428 assert(DirInfo && 429 "The directory of a virtual file should already be in the cache."); 430 431 // Check to see if the file exists. If so, drop the virtual file 432 llvm::vfs::Status Status; 433 const char *InterndFileName = NamedFileEnt.first().data(); 434 if (!getStatValue(InterndFileName, Status, true, nullptr)) { 435 Status = llvm::vfs::Status( 436 Status.getName(), Status.getUniqueID(), 437 llvm::sys::toTimePoint(ModificationTime), 438 Status.getUser(), Status.getGroup(), Size, 439 Status.getType(), Status.getPermissions()); 440 441 auto &RealFE = UniqueRealFiles[Status.getUniqueID()]; 442 if (RealFE) { 443 // If we had already opened this file, close it now so we don't 444 // leak the descriptor. We're not going to use the file 445 // descriptor anyway, since this is a virtual file. 446 if (RealFE->File) 447 RealFE->closeFile(); 448 // If we already have an entry with this inode, return it. 449 // 450 // FIXME: Surely this should add a reference by the new name, and return 451 // it instead... 452 NamedFileEnt.second = FileEntryRef::MapValue(*RealFE, *DirInfo); 453 return FileEntryRef(NamedFileEnt); 454 } 455 // File exists, but no entry - create it. 456 RealFE = new (FilesAlloc.Allocate()) FileEntry(); 457 RealFE->UniqueID = Status.getUniqueID(); 458 RealFE->IsNamedPipe = 459 Status.getType() == llvm::sys::fs::file_type::fifo_file; 460 fillRealPathName(RealFE, Status.getName()); 461 462 UFE = RealFE; 463 } else { 464 // File does not exist, create a virtual entry. 465 UFE = new (FilesAlloc.Allocate()) FileEntry(); 466 VirtualFileEntries.push_back(UFE); 467 } 468 469 NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo); 470 UFE->LastRef = FileEntryRef(NamedFileEnt); 471 UFE->Size = Size; 472 UFE->ModTime = ModificationTime; 473 UFE->Dir = &DirInfo->getDirEntry(); 474 UFE->UID = NextFileUID++; 475 UFE->File.reset(); 476 return FileEntryRef(NamedFileEnt); 477 } 478 479 llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) { 480 // Stat of the file and return nullptr if it doesn't exist. 481 llvm::vfs::Status Status; 482 if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr)) 483 return None; 484 485 if (!SeenBypassFileEntries) 486 SeenBypassFileEntries = std::make_unique< 487 llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>(); 488 489 // If we've already bypassed just use the existing one. 490 auto Insertion = SeenBypassFileEntries->insert( 491 {VF.getName(), std::errc::no_such_file_or_directory}); 492 if (!Insertion.second) 493 return FileEntryRef(*Insertion.first); 494 495 // Fill in the new entry from the stat. 496 FileEntry *BFE = new (FilesAlloc.Allocate()) FileEntry(); 497 BypassFileEntries.push_back(BFE); 498 Insertion.first->second = FileEntryRef::MapValue(*BFE, VF.getDir()); 499 BFE->LastRef = FileEntryRef(*Insertion.first); 500 BFE->Size = Status.getSize(); 501 BFE->Dir = VF.getFileEntry().Dir; 502 BFE->ModTime = llvm::sys::toTimeT(Status.getLastModificationTime()); 503 BFE->UID = NextFileUID++; 504 505 // Save the entry in the bypass table and return. 506 return FileEntryRef(*Insertion.first); 507 } 508 509 bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const { 510 StringRef pathRef(path.data(), path.size()); 511 512 if (FileSystemOpts.WorkingDir.empty() 513 || llvm::sys::path::is_absolute(pathRef)) 514 return false; 515 516 SmallString<128> NewPath(FileSystemOpts.WorkingDir); 517 llvm::sys::path::append(NewPath, pathRef); 518 path = NewPath; 519 return true; 520 } 521 522 bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const { 523 bool Changed = FixupRelativePath(Path); 524 525 if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) { 526 FS->makeAbsolute(Path); 527 Changed = true; 528 } 529 530 return Changed; 531 } 532 533 void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) { 534 llvm::SmallString<128> AbsPath(FileName); 535 // This is not the same as `VFS::getRealPath()`, which resolves symlinks 536 // but can be very expensive on real file systems. 537 // FIXME: the semantic of RealPathName is unclear, and the name might be 538 // misleading. We need to clean up the interface here. 539 makeAbsolutePath(AbsPath); 540 llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true); 541 UFE->RealPathName = std::string(AbsPath.str()); 542 } 543 544 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 545 FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile, 546 bool RequiresNullTerminator) { 547 // If the content is living on the file entry, return a reference to it. 548 if (Entry->Content) 549 return llvm::MemoryBuffer::getMemBuffer(Entry->Content->getMemBufferRef()); 550 551 uint64_t FileSize = Entry->getSize(); 552 // If there's a high enough chance that the file have changed since we 553 // got its size, force a stat before opening it. 554 if (isVolatile || Entry->isNamedPipe()) 555 FileSize = -1; 556 557 StringRef Filename = Entry->getName(); 558 // If the file is already open, use the open file descriptor. 559 if (Entry->File) { 560 auto Result = Entry->File->getBuffer(Filename, FileSize, 561 RequiresNullTerminator, isVolatile); 562 Entry->closeFile(); 563 return Result; 564 } 565 566 // Otherwise, open the file. 567 return getBufferForFileImpl(Filename, FileSize, isVolatile, 568 RequiresNullTerminator); 569 } 570 571 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 572 FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize, 573 bool isVolatile, 574 bool RequiresNullTerminator) { 575 if (FileSystemOpts.WorkingDir.empty()) 576 return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator, 577 isVolatile); 578 579 SmallString<128> FilePath(Filename); 580 FixupRelativePath(FilePath); 581 return FS->getBufferForFile(FilePath, FileSize, RequiresNullTerminator, 582 isVolatile); 583 } 584 585 /// getStatValue - Get the 'stat' information for the specified path, 586 /// using the cache to accelerate it if possible. This returns true 587 /// if the path points to a virtual file or does not exist, or returns 588 /// false if it's an existent real file. If FileDescriptor is NULL, 589 /// do directory look-up instead of file look-up. 590 std::error_code 591 FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status, 592 bool isFile, std::unique_ptr<llvm::vfs::File> *F) { 593 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be 594 // absolute! 595 if (FileSystemOpts.WorkingDir.empty()) 596 return FileSystemStatCache::get(Path, Status, isFile, F, 597 StatCache.get(), *FS); 598 599 SmallString<128> FilePath(Path); 600 FixupRelativePath(FilePath); 601 602 return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F, 603 StatCache.get(), *FS); 604 } 605 606 std::error_code 607 FileManager::getNoncachedStatValue(StringRef Path, 608 llvm::vfs::Status &Result) { 609 SmallString<128> FilePath(Path); 610 FixupRelativePath(FilePath); 611 612 llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str()); 613 if (!S) 614 return S.getError(); 615 Result = *S; 616 return std::error_code(); 617 } 618 619 void FileManager::GetUniqueIDMapping( 620 SmallVectorImpl<const FileEntry *> &UIDToFiles) const { 621 UIDToFiles.clear(); 622 UIDToFiles.resize(NextFileUID); 623 624 // Map file entries 625 for (llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>, 626 llvm::BumpPtrAllocator>::const_iterator 627 FE = SeenFileEntries.begin(), 628 FEEnd = SeenFileEntries.end(); 629 FE != FEEnd; ++FE) 630 if (llvm::ErrorOr<FileEntryRef::MapValue> Entry = FE->getValue()) { 631 if (const auto *FE = Entry->V.dyn_cast<FileEntry *>()) 632 UIDToFiles[FE->getUID()] = FE; 633 } 634 635 // Map virtual file entries 636 for (const auto &VFE : VirtualFileEntries) 637 UIDToFiles[VFE->getUID()] = VFE; 638 } 639 640 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) { 641 llvm::DenseMap<const void *, llvm::StringRef>::iterator Known 642 = CanonicalNames.find(Dir); 643 if (Known != CanonicalNames.end()) 644 return Known->second; 645 646 StringRef CanonicalName(Dir->getName()); 647 648 SmallString<4096> CanonicalNameBuf; 649 if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf)) 650 CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage); 651 652 CanonicalNames.insert({Dir, CanonicalName}); 653 return CanonicalName; 654 } 655 656 StringRef FileManager::getCanonicalName(const FileEntry *File) { 657 llvm::DenseMap<const void *, llvm::StringRef>::iterator Known 658 = CanonicalNames.find(File); 659 if (Known != CanonicalNames.end()) 660 return Known->second; 661 662 StringRef CanonicalName(File->getName()); 663 664 SmallString<4096> CanonicalNameBuf; 665 if (!FS->getRealPath(File->getName(), CanonicalNameBuf)) 666 CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage); 667 668 CanonicalNames.insert({File, CanonicalName}); 669 return CanonicalName; 670 } 671 672 void FileManager::PrintStats() const { 673 llvm::errs() << "\n*** File Manager Stats:\n"; 674 llvm::errs() << UniqueRealFiles.size() << " real files found, " 675 << UniqueRealDirs.size() << " real dirs found.\n"; 676 llvm::errs() << VirtualFileEntries.size() << " virtual files found, " 677 << VirtualDirectoryEntries.size() << " virtual dirs found.\n"; 678 llvm::errs() << NumDirLookups << " dir lookups, " 679 << NumDirCacheMisses << " dir cache misses.\n"; 680 llvm::errs() << NumFileLookups << " file lookups, " 681 << NumFileCacheMisses << " file cache misses.\n"; 682 683 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; 684 } 685