1226efd35SChris Lattner //===--- FileManager.cpp - File System Probing and Caching ----------------===//
27a51313dSChris Lattner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67a51313dSChris Lattner //
77a51313dSChris Lattner //===----------------------------------------------------------------------===//
87a51313dSChris Lattner //
97a51313dSChris Lattner //  This file implements the FileManager interface.
107a51313dSChris Lattner //
117a51313dSChris Lattner //===----------------------------------------------------------------------===//
127a51313dSChris Lattner //
137a51313dSChris Lattner // TODO: This should index all interesting directories with dirent calls.
147a51313dSChris Lattner //  getdirentries ?
157a51313dSChris Lattner //  opendir/readdir_r/closedir ?
167a51313dSChris Lattner //
177a51313dSChris Lattner //===----------------------------------------------------------------------===//
187a51313dSChris Lattner 
197a51313dSChris Lattner #include "clang/Basic/FileManager.h"
20226efd35SChris Lattner #include "clang/Basic/FileSystemStatCache.h"
217a51313dSChris Lattner #include "llvm/ADT/SmallString.h"
223a02247dSChandler Carruth #include "llvm/Config/llvm-config.h"
23d2725a31SDavid Blaikie #include "llvm/ADT/STLExtras.h"
24740857faSMichael J. Spencer #include "llvm/Support/FileSystem.h"
2571731d6bSArgyrios Kyrtzidis #include "llvm/Support/MemoryBuffer.h"
268aaf4995SMichael J. Spencer #include "llvm/Support/Path.h"
273a02247dSChandler Carruth #include "llvm/Support/raw_ostream.h"
2835b79c24SEugene Zelenko #include <algorithm>
2935b79c24SEugene Zelenko #include <cassert>
3035b79c24SEugene Zelenko #include <climits>
3135b79c24SEugene Zelenko #include <cstdint>
3235b79c24SEugene Zelenko #include <cstdlib>
3326db6481SBenjamin Kramer #include <string>
3435b79c24SEugene Zelenko #include <utility>
35278038b4SChris Lattner 
367a51313dSChris Lattner using namespace clang;
377a51313dSChris Lattner 
385c04bd81STed Kremenek //===----------------------------------------------------------------------===//
395c04bd81STed Kremenek // Common logic.
405c04bd81STed Kremenek //===----------------------------------------------------------------------===//
417a51313dSChris Lattner 
42c8130a74SBen Langmuir FileManager::FileManager(const FileSystemOptions &FSO,
43fc51490bSJonas Devlieghere                          IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
44f6021ecdSBenjamin Kramer     : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
45f6021ecdSBenjamin Kramer       SeenFileEntries(64), NextFileUID(0) {
467a51313dSChris Lattner   NumDirLookups = NumFileLookups = 0;
477a51313dSChris Lattner   NumDirCacheMisses = NumFileCacheMisses = 0;
48c8130a74SBen Langmuir 
49c8130a74SBen Langmuir   // If the caller doesn't provide a virtual file system, just grab the real
50c8130a74SBen Langmuir   // file system.
51f6021ecdSBenjamin Kramer   if (!this->FS)
52fc51490bSJonas Devlieghere     this->FS = llvm::vfs::getRealFileSystem();
537a51313dSChris Lattner }
547a51313dSChris Lattner 
55d2725a31SDavid Blaikie FileManager::~FileManager() = default;
567a51313dSChris Lattner 
57d92b1ae1SAlex Lorenz void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
58d2eb58abSDouglas Gregor   assert(statCache && "No stat cache provided?");
5923430ccbSDavid Blaikie   StatCache = std::move(statCache);
60d2eb58abSDouglas Gregor }
61d2eb58abSDouglas Gregor 
62d92b1ae1SAlex Lorenz void FileManager::clearStatCache() { StatCache.reset(); }
633aad855aSManuel Klimek 
649fc8faf9SAdrian Prantl /// Retrieve the directory that the given file name resides in.
65e1dd3e2cSZhanyong Wan /// Filename can point to either a real file or a virtual file.
66407e2124SDouglas Gregor static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
671735f4e7SDouglas Gregor                                                   StringRef Filename,
681735f4e7SDouglas Gregor                                                   bool CacheFailure) {
69f3c0ff73SZhanyong Wan   if (Filename.empty())
70f1186c5aSCraig Topper     return nullptr;
71e1dd3e2cSZhanyong Wan 
72f3c0ff73SZhanyong Wan   if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
73f1186c5aSCraig Topper     return nullptr; // If Filename is a directory.
740c0e8040SChris Lattner 
750e62c1ccSChris Lattner   StringRef DirName = llvm::sys::path::parent_path(Filename);
760c0e8040SChris Lattner   // Use the current directory if file has no path component.
77f3c0ff73SZhanyong Wan   if (DirName.empty())
78f3c0ff73SZhanyong Wan     DirName = ".";
790c0e8040SChris Lattner 
801735f4e7SDouglas Gregor   return FileMgr.getDirectory(DirName, CacheFailure);
81407e2124SDouglas Gregor }
82407e2124SDouglas Gregor 
83e1dd3e2cSZhanyong Wan /// Add all ancestors of the given path (pointing to either a file or
84e1dd3e2cSZhanyong Wan /// a directory) as virtual directories.
850e62c1ccSChris Lattner void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
860e62c1ccSChris Lattner   StringRef DirName = llvm::sys::path::parent_path(Path);
87f3c0ff73SZhanyong Wan   if (DirName.empty())
881834dc75SDavid Majnemer     DirName = ".";
89e1dd3e2cSZhanyong Wan 
90*018ab5faSRichard Smith   auto &NamedDirEnt = *SeenDirEntries.insert({DirName, nullptr}).first;
91e1dd3e2cSZhanyong Wan 
92e1dd3e2cSZhanyong Wan   // When caching a virtual directory, we always cache its ancestors
93e1dd3e2cSZhanyong Wan   // at the same time.  Therefore, if DirName is already in the cache,
94e1dd3e2cSZhanyong Wan   // we don't need to recurse as its ancestors must also already be in
95*018ab5faSRichard Smith   // the cache (or it's a known non-virtual directory).
96*018ab5faSRichard Smith   if (NamedDirEnt.second)
97e1dd3e2cSZhanyong Wan     return;
98e1dd3e2cSZhanyong Wan 
99e1dd3e2cSZhanyong Wan   // Add the virtual directory to the cache.
100d2725a31SDavid Blaikie   auto UDE = llvm::make_unique<DirectoryEntry>();
1010df59d8cSMehdi Amini   UDE->Name = NamedDirEnt.first();
102d2725a31SDavid Blaikie   NamedDirEnt.second = UDE.get();
103d2725a31SDavid Blaikie   VirtualDirectoryEntries.push_back(std::move(UDE));
104e1dd3e2cSZhanyong Wan 
105e1dd3e2cSZhanyong Wan   // Recursively add the other ancestors.
106e1dd3e2cSZhanyong Wan   addAncestorsAsVirtualDirs(DirName);
107e1dd3e2cSZhanyong Wan }
108e1dd3e2cSZhanyong Wan 
1091735f4e7SDouglas Gregor const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
1101735f4e7SDouglas Gregor                                                 bool CacheFailure) {
1118bd8ee76SNAKAMURA Takumi   // stat doesn't like trailing separators except for root directory.
11232f1acf1SNAKAMURA Takumi   // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
11332f1acf1SNAKAMURA Takumi   // (though it can strip '\\')
1148bd8ee76SNAKAMURA Takumi   if (DirName.size() > 1 &&
1158bd8ee76SNAKAMURA Takumi       DirName != llvm::sys::path::root_path(DirName) &&
1168bd8ee76SNAKAMURA Takumi       llvm::sys::path::is_separator(DirName.back()))
11732f1acf1SNAKAMURA Takumi     DirName = DirName.substr(0, DirName.size()-1);
1181865df49SNico Weber #ifdef _WIN32
119ee30546cSRafael Espindola   // Fixing a problem with "clang C:test.c" on Windows.
120ee30546cSRafael Espindola   // Stat("C:") does not recognize "C:" as a valid directory
121ee30546cSRafael Espindola   std::string DirNameStr;
122ee30546cSRafael Espindola   if (DirName.size() > 1 && DirName.back() == ':' &&
123ee30546cSRafael Espindola       DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
124ee30546cSRafael Espindola     DirNameStr = DirName.str() + '.';
125ee30546cSRafael Espindola     DirName = DirNameStr;
126ee30546cSRafael Espindola   }
127ee30546cSRafael Espindola #endif
12832f1acf1SNAKAMURA Takumi 
1297a51313dSChris Lattner   ++NumDirLookups;
1307a51313dSChris Lattner 
131e1dd3e2cSZhanyong Wan   // See if there was already an entry in the map.  Note that the map
132e1dd3e2cSZhanyong Wan   // contains both virtual and real directories.
133*018ab5faSRichard Smith   auto SeenDirInsertResult = SeenDirEntries.insert({DirName, nullptr});
134*018ab5faSRichard Smith   if (!SeenDirInsertResult.second)
135*018ab5faSRichard Smith     return SeenDirInsertResult.first->second;
1367a51313dSChris Lattner 
137*018ab5faSRichard Smith   // We've not seen this before. Fill it in.
1387a51313dSChris Lattner   ++NumDirCacheMisses;
139*018ab5faSRichard Smith   auto &NamedDirEnt = *SeenDirInsertResult.first;
140*018ab5faSRichard Smith   assert(!NamedDirEnt.second && "should be newly-created");
1417a51313dSChris Lattner 
1427a51313dSChris Lattner   // Get the null-terminated directory name as stored as the key of the
143e1dd3e2cSZhanyong Wan   // SeenDirEntries map.
1440df59d8cSMehdi Amini   StringRef InterndDirName = NamedDirEnt.first();
1457a51313dSChris Lattner 
1467a51313dSChris Lattner   // Check to see if the directory exists.
147f8f91b89SRafael Espindola   FileData Data;
148f1186c5aSCraig Topper   if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) {
149e1dd3e2cSZhanyong Wan     // There's no real directory at the given path.
1501735f4e7SDouglas Gregor     if (!CacheFailure)
1511735f4e7SDouglas Gregor       SeenDirEntries.erase(DirName);
152f1186c5aSCraig Topper     return nullptr;
153e1dd3e2cSZhanyong Wan   }
1547a51313dSChris Lattner 
155e1dd3e2cSZhanyong Wan   // It exists.  See if we have already opened a directory with the
156e1dd3e2cSZhanyong Wan   // same inode (this occurs on Unix-like systems when one dir is
157e1dd3e2cSZhanyong Wan   // symlinked to another, for example) or the same path (on
158e1dd3e2cSZhanyong Wan   // Windows).
159c9b7234eSBen Langmuir   DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID];
1607a51313dSChris Lattner 
16113156b68SDavid Blaikie   NamedDirEnt.second = &UDE;
1620df59d8cSMehdi Amini   if (UDE.getName().empty()) {
163e1dd3e2cSZhanyong Wan     // We don't have this directory yet, add it.  We use the string
164e1dd3e2cSZhanyong Wan     // key from the SeenDirEntries map as the string.
1657a51313dSChris Lattner     UDE.Name  = InterndDirName;
166e1dd3e2cSZhanyong Wan   }
167e1dd3e2cSZhanyong Wan 
1687a51313dSChris Lattner   return &UDE;
1697a51313dSChris Lattner }
1707a51313dSChris Lattner 
1711735f4e7SDouglas Gregor const FileEntry *FileManager::getFile(StringRef Filename, bool openFile,
1721735f4e7SDouglas Gregor                                       bool CacheFailure) {
1737a51313dSChris Lattner   ++NumFileLookups;
1747a51313dSChris Lattner 
1757a51313dSChris Lattner   // See if there is already an entry in the map.
176*018ab5faSRichard Smith   auto SeenFileInsertResult = SeenFileEntries.insert({Filename, nullptr});
177*018ab5faSRichard Smith   if (!SeenFileInsertResult.second)
178*018ab5faSRichard Smith     return SeenFileInsertResult.first->second;
1797a51313dSChris Lattner 
180*018ab5faSRichard Smith   // We've not seen this before. Fill it in.
181e84385feSSam McCall   ++NumFileCacheMisses;
182*018ab5faSRichard Smith   auto &NamedFileEnt = *SeenFileInsertResult.first;
183*018ab5faSRichard Smith   assert(!NamedFileEnt.second && "should be newly-created");
184fa361206SSam McCall 
1857a51313dSChris Lattner   // Get the null-terminated file name as stored as the key of the
186e1dd3e2cSZhanyong Wan   // SeenFileEntries map.
1870df59d8cSMehdi Amini   StringRef InterndFileName = NamedFileEnt.first();
1887a51313dSChris Lattner 
189966b25b9SChris Lattner   // Look up the directory for the file.  When looking up something like
190966b25b9SChris Lattner   // sys/foo.h we'll discover all of the search directories that have a 'sys'
191966b25b9SChris Lattner   // subdirectory.  This will let us avoid having to waste time on known-to-fail
192966b25b9SChris Lattner   // searches when we go to find sys/bar.h, because all the search directories
193966b25b9SChris Lattner   // without a 'sys' subdir will get a cached failure result.
1941735f4e7SDouglas Gregor   const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
1951735f4e7SDouglas Gregor                                                        CacheFailure);
196f1186c5aSCraig Topper   if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist.
1971735f4e7SDouglas Gregor     if (!CacheFailure)
1981735f4e7SDouglas Gregor       SeenFileEntries.erase(Filename);
1991735f4e7SDouglas Gregor 
200f1186c5aSCraig Topper     return nullptr;
2011735f4e7SDouglas Gregor   }
202407e2124SDouglas Gregor 
2037a51313dSChris Lattner   // FIXME: Use the directory info to prune this, before doing the stat syscall.
2047a51313dSChris Lattner   // FIXME: This will reduce the # syscalls.
2057a51313dSChris Lattner 
206*018ab5faSRichard Smith   // Check to see if the file exists.
207fc51490bSJonas Devlieghere   std::unique_ptr<llvm::vfs::File> F;
208f8f91b89SRafael Espindola   FileData Data;
209f1186c5aSCraig Topper   if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) {
210e1dd3e2cSZhanyong Wan     // There's no real file at the given path.
2111735f4e7SDouglas Gregor     if (!CacheFailure)
2121735f4e7SDouglas Gregor       SeenFileEntries.erase(Filename);
2131735f4e7SDouglas Gregor 
214f1186c5aSCraig Topper     return nullptr;
215e1dd3e2cSZhanyong Wan   }
2167a51313dSChris Lattner 
217ab01d4bbSPatrik Hagglund   assert((openFile || !F) && "undesired open file");
218d6278e32SArgyrios Kyrtzidis 
2197a51313dSChris Lattner   // It exists.  See if we have already opened a file with the same inode.
2207a51313dSChris Lattner   // This occurs when one dir is symlinked to another, for example.
221c9b7234eSBen Langmuir   FileEntry &UFE = UniqueRealFiles[Data.UniqueID];
2227a51313dSChris Lattner 
22313156b68SDavid Blaikie   NamedFileEnt.second = &UFE;
224ab86fbe4SBen Langmuir 
225ab86fbe4SBen Langmuir   // If the name returned by getStatValue is different than Filename, re-intern
226ab86fbe4SBen Langmuir   // the name.
227ab86fbe4SBen Langmuir   if (Data.Name != Filename) {
228*018ab5faSRichard Smith     auto &NamedFileEnt = *SeenFileEntries.insert({Data.Name, &UFE}).first;
22913156b68SDavid Blaikie     assert(NamedFileEnt.second == &UFE &&
230ab86fbe4SBen Langmuir            "filename from getStatValue() refers to wrong file");
23113156b68SDavid Blaikie     InterndFileName = NamedFileEnt.first().data();
232ab86fbe4SBen Langmuir   }
233ab86fbe4SBen Langmuir 
234c8a71468SBen Langmuir   if (UFE.isValid()) { // Already have an entry with this inode, return it.
2355de00f3bSBen Langmuir 
2365de00f3bSBen Langmuir     // FIXME: this hack ensures that if we look up a file by a virtual path in
2375de00f3bSBen Langmuir     // the VFS that the getDir() will have the virtual path, even if we found
2385de00f3bSBen Langmuir     // the file by a 'real' path first. This is required in order to find a
2395de00f3bSBen Langmuir     // module's structure when its headers/module map are mapped in the VFS.
2405de00f3bSBen Langmuir     // We should remove this as soon as we can properly support a file having
2415de00f3bSBen Langmuir     // multiple names.
2425de00f3bSBen Langmuir     if (DirInfo != UFE.Dir && Data.IsVFSMapped)
2435de00f3bSBen Langmuir       UFE.Dir = DirInfo;
2445de00f3bSBen Langmuir 
245c0ff9908SManuel Klimek     // Always update the name to use the last name by which a file was accessed.
246c0ff9908SManuel Klimek     // FIXME: Neither this nor always using the first name is correct; we want
247c0ff9908SManuel Klimek     // to switch towards a design where we return a FileName object that
248c0ff9908SManuel Klimek     // encapsulates both the name by which the file was accessed and the
249c0ff9908SManuel Klimek     // corresponding FileEntry.
250ab86fbe4SBen Langmuir     UFE.Name = InterndFileName;
251c0ff9908SManuel Klimek 
2527a51313dSChris Lattner     return &UFE;
253dd278430SChris Lattner   }
2547a51313dSChris Lattner 
255c9b7234eSBen Langmuir   // Otherwise, we don't have this file yet, add it.
256ab86fbe4SBen Langmuir   UFE.Name    = InterndFileName;
257f8f91b89SRafael Espindola   UFE.Size = Data.Size;
258f8f91b89SRafael Espindola   UFE.ModTime = Data.ModTime;
2597a51313dSChris Lattner   UFE.Dir     = DirInfo;
2607a51313dSChris Lattner   UFE.UID     = NextFileUID++;
261c9b7234eSBen Langmuir   UFE.UniqueID = Data.UniqueID;
262c9b7234eSBen Langmuir   UFE.IsNamedPipe = Data.IsNamedPipe;
263c9b7234eSBen Langmuir   UFE.InPCH = Data.InPCH;
264fa361206SSam McCall   UFE.File = std::move(F);
265c8a71468SBen Langmuir   UFE.IsValid = true;
266ddbabc6bSSimon Marchi 
267fa361206SSam McCall   if (UFE.File) {
268fa361206SSam McCall     if (auto PathName = UFE.File->getName())
269fa361206SSam McCall       fillRealPathName(&UFE, *PathName);
270fa361206SSam McCall   }
2717a51313dSChris Lattner   return &UFE;
2727a51313dSChris Lattner }
2737a51313dSChris Lattner 
274407e2124SDouglas Gregor const FileEntry *
2750e62c1ccSChris Lattner FileManager::getVirtualFile(StringRef Filename, off_t Size,
2765159f616SChris Lattner                             time_t ModificationTime) {
277407e2124SDouglas Gregor   ++NumFileLookups;
278407e2124SDouglas Gregor 
279*018ab5faSRichard Smith   // See if there is already an entry in the map for an existing file.
280*018ab5faSRichard Smith   auto &NamedFileEnt = *SeenFileEntries.insert({Filename, nullptr}).first;
281*018ab5faSRichard Smith   if (NamedFileEnt.second)
28213156b68SDavid Blaikie     return NamedFileEnt.second;
283407e2124SDouglas Gregor 
284*018ab5faSRichard Smith   // We've not seen this before, or the file is cached as non-existent.
285407e2124SDouglas Gregor   ++NumFileCacheMisses;
286e1dd3e2cSZhanyong Wan   addAncestorsAsVirtualDirs(Filename);
287f1186c5aSCraig Topper   FileEntry *UFE = nullptr;
288e1dd3e2cSZhanyong Wan 
289e1dd3e2cSZhanyong Wan   // Now that all ancestors of Filename are in the cache, the
290e1dd3e2cSZhanyong Wan   // following call is guaranteed to find the DirectoryEntry from the
291e1dd3e2cSZhanyong Wan   // cache.
2921735f4e7SDouglas Gregor   const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename,
2931735f4e7SDouglas Gregor                                                        /*CacheFailure=*/true);
294e1dd3e2cSZhanyong Wan   assert(DirInfo &&
295e1dd3e2cSZhanyong Wan          "The directory of a virtual file should already be in the cache.");
296e1dd3e2cSZhanyong Wan 
297606c4ac3SDouglas Gregor   // Check to see if the file exists. If so, drop the virtual file
298f8f91b89SRafael Espindola   FileData Data;
29913156b68SDavid Blaikie   const char *InterndFileName = NamedFileEnt.first().data();
300f1186c5aSCraig Topper   if (getStatValue(InterndFileName, Data, true, nullptr) == 0) {
301f8f91b89SRafael Espindola     Data.Size = Size;
302f8f91b89SRafael Espindola     Data.ModTime = ModificationTime;
303c9b7234eSBen Langmuir     UFE = &UniqueRealFiles[Data.UniqueID];
304606c4ac3SDouglas Gregor 
30513156b68SDavid Blaikie     NamedFileEnt.second = UFE;
306606c4ac3SDouglas Gregor 
307606c4ac3SDouglas Gregor     // If we had already opened this file, close it now so we don't
308606c4ac3SDouglas Gregor     // leak the descriptor. We're not going to use the file
309606c4ac3SDouglas Gregor     // descriptor anyway, since this is a virtual file.
310c8130a74SBen Langmuir     if (UFE->File)
311c8130a74SBen Langmuir       UFE->closeFile();
312606c4ac3SDouglas Gregor 
313606c4ac3SDouglas Gregor     // If we already have an entry with this inode, return it.
314c8a71468SBen Langmuir     if (UFE->isValid())
315606c4ac3SDouglas Gregor       return UFE;
316c9b7234eSBen Langmuir 
317c9b7234eSBen Langmuir     UFE->UniqueID = Data.UniqueID;
318c9b7234eSBen Langmuir     UFE->IsNamedPipe = Data.IsNamedPipe;
319c9b7234eSBen Langmuir     UFE->InPCH = Data.InPCH;
320e9870c0cSKadir Cetinkaya     fillRealPathName(UFE, Data.Name);
321*018ab5faSRichard Smith   } else {
322d2725a31SDavid Blaikie     VirtualFileEntries.push_back(llvm::make_unique<FileEntry>());
323d2725a31SDavid Blaikie     UFE = VirtualFileEntries.back().get();
32413156b68SDavid Blaikie     NamedFileEnt.second = UFE;
325606c4ac3SDouglas Gregor   }
326407e2124SDouglas Gregor 
3279624b695SChris Lattner   UFE->Name    = InterndFileName;
328407e2124SDouglas Gregor   UFE->Size    = Size;
329407e2124SDouglas Gregor   UFE->ModTime = ModificationTime;
330407e2124SDouglas Gregor   UFE->Dir     = DirInfo;
331407e2124SDouglas Gregor   UFE->UID     = NextFileUID++;
332dfffaf57SErik Verbruggen   UFE->IsValid = true;
333c8130a74SBen Langmuir   UFE->File.reset();
334407e2124SDouglas Gregor   return UFE;
335407e2124SDouglas Gregor }
336407e2124SDouglas Gregor 
337c56419edSArgyrios Kyrtzidis bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
3380e62c1ccSChris Lattner   StringRef pathRef(path.data(), path.size());
339b5c356a4SAnders Carlsson 
3409ba8fb1eSAnders Carlsson   if (FileSystemOpts.WorkingDir.empty()
3419ba8fb1eSAnders Carlsson       || llvm::sys::path::is_absolute(pathRef))
342c56419edSArgyrios Kyrtzidis     return false;
34371731d6bSArgyrios Kyrtzidis 
3442c1dd271SDylan Noblesmith   SmallString<128> NewPath(FileSystemOpts.WorkingDir);
345b5c356a4SAnders Carlsson   llvm::sys::path::append(NewPath, pathRef);
3466e640998SChris Lattner   path = NewPath;
347c56419edSArgyrios Kyrtzidis   return true;
348c56419edSArgyrios Kyrtzidis }
349c56419edSArgyrios Kyrtzidis 
350c56419edSArgyrios Kyrtzidis bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
351c56419edSArgyrios Kyrtzidis   bool Changed = FixupRelativePath(Path);
352c56419edSArgyrios Kyrtzidis 
353c56419edSArgyrios Kyrtzidis   if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
35447035c02SIlya Biryukov     FS->makeAbsolute(Path);
355c56419edSArgyrios Kyrtzidis     Changed = true;
356c56419edSArgyrios Kyrtzidis   }
357c56419edSArgyrios Kyrtzidis 
358c56419edSArgyrios Kyrtzidis   return Changed;
3596e640998SChris Lattner }
3606e640998SChris Lattner 
361e9870c0cSKadir Cetinkaya void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
362e9870c0cSKadir Cetinkaya   llvm::SmallString<128> AbsPath(FileName);
363e9870c0cSKadir Cetinkaya   // This is not the same as `VFS::getRealPath()`, which resolves symlinks
364e9870c0cSKadir Cetinkaya   // but can be very expensive on real file systems.
365e9870c0cSKadir Cetinkaya   // FIXME: the semantic of RealPathName is unclear, and the name might be
366e9870c0cSKadir Cetinkaya   // misleading. We need to clean up the interface here.
367e9870c0cSKadir Cetinkaya   makeAbsolutePath(AbsPath);
368e9870c0cSKadir Cetinkaya   llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
369e9870c0cSKadir Cetinkaya   UFE->RealPathName = AbsPath.str();
370e9870c0cSKadir Cetinkaya }
371e9870c0cSKadir Cetinkaya 
372a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
373a885796dSBenjamin Kramer FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
374a885796dSBenjamin Kramer                               bool ShouldCloseOpenFile) {
3756d7833f1SArgyrios Kyrtzidis   uint64_t FileSize = Entry->getSize();
3766d7833f1SArgyrios Kyrtzidis   // If there's a high enough chance that the file have changed since we
3776d7833f1SArgyrios Kyrtzidis   // got its size, force a stat before opening it.
3786d7833f1SArgyrios Kyrtzidis   if (isVolatile)
3796d7833f1SArgyrios Kyrtzidis     FileSize = -1;
3806d7833f1SArgyrios Kyrtzidis 
381004b9c7aSMehdi Amini   StringRef Filename = Entry->getName();
3825ea7d07dSChris Lattner   // If the file is already open, use the open file descriptor.
383c8130a74SBen Langmuir   if (Entry->File) {
384a885796dSBenjamin Kramer     auto Result =
385a885796dSBenjamin Kramer         Entry->File->getBuffer(Filename, FileSize,
38626d56393SArgyrios Kyrtzidis                                /*RequiresNullTerminator=*/true, isVolatile);
3879801b253SBen Langmuir     // FIXME: we need a set of APIs that can make guarantees about whether a
3889801b253SBen Langmuir     // FileEntry is open or not.
3899801b253SBen Langmuir     if (ShouldCloseOpenFile)
390c8130a74SBen Langmuir       Entry->closeFile();
3916406f7b8SRafael Espindola     return Result;
3925ea7d07dSChris Lattner   }
3936e640998SChris Lattner 
3945ea7d07dSChris Lattner   // Otherwise, open the file.
395669b0b15SArgyrios Kyrtzidis 
396a885796dSBenjamin Kramer   if (FileSystemOpts.WorkingDir.empty())
397a885796dSBenjamin Kramer     return FS->getBufferForFile(Filename, FileSize,
39826d56393SArgyrios Kyrtzidis                                 /*RequiresNullTerminator=*/true, isVolatile);
3995ea7d07dSChris Lattner 
4002c1dd271SDylan Noblesmith   SmallString<128> FilePath(Entry->getName());
401878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
40292e1b62dSYaron Keren   return FS->getBufferForFile(FilePath, FileSize,
40326d56393SArgyrios Kyrtzidis                               /*RequiresNullTerminator=*/true, isVolatile);
40426b5c190SChris Lattner }
40526b5c190SChris Lattner 
406a885796dSBenjamin Kramer llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
4072ebe3a02SIvan Donchevskii FileManager::getBufferForFile(StringRef Filename, bool isVolatile) {
408a885796dSBenjamin Kramer   if (FileSystemOpts.WorkingDir.empty())
4092ebe3a02SIvan Donchevskii     return FS->getBufferForFile(Filename, -1, true, isVolatile);
41026b5c190SChris Lattner 
4112c1dd271SDylan Noblesmith   SmallString<128> FilePath(Filename);
412878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
4132ebe3a02SIvan Donchevskii   return FS->getBufferForFile(FilePath.c_str(), -1, true, isVolatile);
41471731d6bSArgyrios Kyrtzidis }
41571731d6bSArgyrios Kyrtzidis 
416e1dd3e2cSZhanyong Wan /// getStatValue - Get the 'stat' information for the specified path,
417e1dd3e2cSZhanyong Wan /// using the cache to accelerate it if possible.  This returns true
418e1dd3e2cSZhanyong Wan /// if the path points to a virtual file or does not exist, or returns
419e1dd3e2cSZhanyong Wan /// false if it's an existent real file.  If FileDescriptor is NULL,
420e1dd3e2cSZhanyong Wan /// do directory look-up instead of file look-up.
4210df59d8cSMehdi Amini bool FileManager::getStatValue(StringRef Path, FileData &Data, bool isFile,
422fc51490bSJonas Devlieghere                                std::unique_ptr<llvm::vfs::File> *F) {
423226efd35SChris Lattner   // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
424226efd35SChris Lattner   // absolute!
4255769c3dfSChris Lattner   if (FileSystemOpts.WorkingDir.empty())
426c8130a74SBen Langmuir     return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS);
427226efd35SChris Lattner 
4282c1dd271SDylan Noblesmith   SmallString<128> FilePath(Path);
429878b3e2bSAnders Carlsson   FixupRelativePath(FilePath);
43071731d6bSArgyrios Kyrtzidis 
431c8130a74SBen Langmuir   return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F,
432c8130a74SBen Langmuir                                   StatCache.get(), *FS);
43371731d6bSArgyrios Kyrtzidis }
43471731d6bSArgyrios Kyrtzidis 
4350e62c1ccSChris Lattner bool FileManager::getNoncachedStatValue(StringRef Path,
436fc51490bSJonas Devlieghere                                         llvm::vfs::Status &Result) {
4372c1dd271SDylan Noblesmith   SmallString<128> FilePath(Path);
4385e368405SAnders Carlsson   FixupRelativePath(FilePath);
4395e368405SAnders Carlsson 
440fc51490bSJonas Devlieghere   llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
441c8130a74SBen Langmuir   if (!S)
442c8130a74SBen Langmuir     return true;
443c8130a74SBen Langmuir   Result = *S;
444c8130a74SBen Langmuir   return false;
4455e368405SAnders Carlsson }
4465e368405SAnders Carlsson 
447b3074003SAxel Naumann void FileManager::invalidateCache(const FileEntry *Entry) {
448b3074003SAxel Naumann   assert(Entry && "Cannot invalidate a NULL FileEntry");
44938179d96SAxel Naumann 
45038179d96SAxel Naumann   SeenFileEntries.erase(Entry->getName());
451b3074003SAxel Naumann 
452b3074003SAxel Naumann   // FileEntry invalidation should not block future optimizations in the file
453b3074003SAxel Naumann   // caches. Possible alternatives are cache truncation (invalidate last N) or
454b3074003SAxel Naumann   // invalidation of the whole cache.
455*018ab5faSRichard Smith   //
456*018ab5faSRichard Smith   // FIXME: This is broken. We sometimes have the same FileEntry* shared
457*018ab5faSRichard Smith   // betweeen multiple SeenFileEntries, so this can leave dangling pointers.
458c9b7234eSBen Langmuir   UniqueRealFiles.erase(Entry->getUniqueID());
45938179d96SAxel Naumann }
46038179d96SAxel Naumann 
46109b6989eSDouglas Gregor void FileManager::GetUniqueIDMapping(
4620e62c1ccSChris Lattner                    SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
46309b6989eSDouglas Gregor   UIDToFiles.clear();
46409b6989eSDouglas Gregor   UIDToFiles.resize(NextFileUID);
46509b6989eSDouglas Gregor 
46609b6989eSDouglas Gregor   // Map file entries
46709b6989eSDouglas Gregor   for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
468e1dd3e2cSZhanyong Wan          FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
46909b6989eSDouglas Gregor        FE != FEEnd; ++FE)
470*018ab5faSRichard Smith     if (FE->getValue())
47109b6989eSDouglas Gregor       UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
47209b6989eSDouglas Gregor 
47309b6989eSDouglas Gregor   // Map virtual file entries
474d2725a31SDavid Blaikie   for (const auto &VFE : VirtualFileEntries)
475d2725a31SDavid Blaikie     UIDToFiles[VFE->getUID()] = VFE.get();
47609b6989eSDouglas Gregor }
477226efd35SChris Lattner 
4786eec06d0SArgyrios Kyrtzidis void FileManager::modifyFileEntry(FileEntry *File,
4796eec06d0SArgyrios Kyrtzidis                                   off_t Size, time_t ModificationTime) {
4806eec06d0SArgyrios Kyrtzidis   File->Size = Size;
4816eec06d0SArgyrios Kyrtzidis   File->ModTime = ModificationTime;
4826eec06d0SArgyrios Kyrtzidis }
4836eec06d0SArgyrios Kyrtzidis 
484e00c8b20SDouglas Gregor StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
485e00c8b20SDouglas Gregor   // FIXME: use llvm::sys::fs::canonical() when it gets implemented
486e00c8b20SDouglas Gregor   llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
487e00c8b20SDouglas Gregor     = CanonicalDirNames.find(Dir);
488e00c8b20SDouglas Gregor   if (Known != CanonicalDirNames.end())
489e00c8b20SDouglas Gregor     return Known->second;
490e00c8b20SDouglas Gregor 
491e00c8b20SDouglas Gregor   StringRef CanonicalName(Dir->getName());
49254cc3c2fSRichard Smith 
4935fb18fecSEric Liu   SmallString<4096> CanonicalNameBuf;
4945fb18fecSEric Liu   if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
495da4690aeSBenjamin Kramer     CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
496e00c8b20SDouglas Gregor 
497*018ab5faSRichard Smith   CanonicalDirNames.insert({Dir, CanonicalName});
498e00c8b20SDouglas Gregor   return CanonicalName;
499e00c8b20SDouglas Gregor }
500226efd35SChris Lattner 
5017a51313dSChris Lattner void FileManager::PrintStats() const {
50289b422c1SBenjamin Kramer   llvm::errs() << "\n*** File Manager Stats:\n";
503e1dd3e2cSZhanyong Wan   llvm::errs() << UniqueRealFiles.size() << " real files found, "
504e1dd3e2cSZhanyong Wan                << UniqueRealDirs.size() << " real dirs found.\n";
505e1dd3e2cSZhanyong Wan   llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
506e1dd3e2cSZhanyong Wan                << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
50789b422c1SBenjamin Kramer   llvm::errs() << NumDirLookups << " dir lookups, "
5087a51313dSChris Lattner                << NumDirCacheMisses << " dir cache misses.\n";
50989b422c1SBenjamin Kramer   llvm::errs() << NumFileLookups << " file lookups, "
5107a51313dSChris Lattner                << NumFileCacheMisses << " file cache misses.\n";
5117a51313dSChris Lattner 
51289b422c1SBenjamin Kramer   //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
5137a51313dSChris Lattner }
514