blob: df3ed2830229e2324aceda4e1ea97139daabbd4e [file] [log] [blame]
Chris Lattner10e286a2010-11-23 19:19:34 +00001//===--- FileManager.cpp - File System Probing and Caching ----------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the FileManager interface.
11//
12//===----------------------------------------------------------------------===//
13//
14// TODO: This should index all interesting directories with dirent calls.
15// getdirentries ?
16// opendir/readdir_r/closedir ?
17//
18//===----------------------------------------------------------------------===//
19
20#include "clang/Basic/FileManager.h"
Chris Lattner10e286a2010-11-23 19:19:34 +000021#include "clang/Basic/FileSystemStatCache.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "llvm/ADT/SmallString.h"
Chris Lattnerc070da42010-08-23 23:50:42 +000023#include "llvm/ADT/StringExtras.h"
Michael J. Spencerfbfd1802010-12-21 16:45:57 +000024#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +000025#include "llvm/Support/MemoryBuffer.h"
Chris Lattnerd57a7ef2009-08-23 22:45:33 +000026#include "llvm/Support/raw_ostream.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000027#include "llvm/Support/Path.h"
Michael J. Spencer3a321e22010-12-09 17:36:38 +000028#include "llvm/Support/system_error.h"
Ted Kremenek6bb816a2008-02-24 03:15:25 +000029#include "llvm/Config/config.h"
Benjamin Kramer458fb102009-09-05 09:49:39 +000030#include <map>
31#include <set>
32#include <string>
Chris Lattner291fcf02010-11-23 21:53:15 +000033
34// FIXME: This is terrible, we need this for ::close.
35#if !defined(_MSC_VER) && !defined(__MINGW32__)
36#include <unistd.h>
37#include <sys/uio.h>
38#else
39#include <io.h>
40#endif
Reid Spencer5f016e22007-07-11 17:01:13 +000041using namespace clang;
42
43// FIXME: Enhance libsystem to support inode and other fields.
44#include <sys/stat.h>
45
Ted Kremenek3d2da3d2008-01-11 20:42:05 +000046/// NON_EXISTENT_DIR - A special value distinct from null that is used to
Reid Spencer5f016e22007-07-11 17:01:13 +000047/// represent a dir name that doesn't exist on the disk.
Ted Kremenek3d2da3d2008-01-11 20:42:05 +000048#define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
Reid Spencer5f016e22007-07-11 17:01:13 +000049
Chris Lattnerf9f77662010-11-23 20:50:22 +000050/// NON_EXISTENT_FILE - A special value distinct from null that is used to
51/// represent a filename that doesn't exist on the disk.
52#define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)
53
54
55FileEntry::~FileEntry() {
56 // If this FileEntry owns an open file descriptor that never got used, close
57 // it.
58 if (FD != -1) ::close(FD);
59}
60
Ted Kremenekcb8d58b2009-01-28 00:27:31 +000061//===----------------------------------------------------------------------===//
62// Windows.
63//===----------------------------------------------------------------------===//
64
Ted Kremenek6bb816a2008-02-24 03:15:25 +000065#ifdef LLVM_ON_WIN32
66
Benjamin Krameraa8b2d92010-11-21 11:32:22 +000067#define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/' || (x) == '\\')
Ted Kremenek6bb816a2008-02-24 03:15:25 +000068
69namespace {
Mike Stump1eb44332009-09-09 15:08:12 +000070 static std::string GetFullPath(const char *relPath) {
Ted Kremenek6bb816a2008-02-24 03:15:25 +000071 char *absPathStrPtr = _fullpath(NULL, relPath, 0);
72 assert(absPathStrPtr && "_fullpath() returned NULL!");
73
74 std::string absPath(absPathStrPtr);
75
76 free(absPathStrPtr);
77 return absPath;
78 }
79}
80
81class FileManager::UniqueDirContainer {
82 /// UniqueDirs - Cache from full path to existing directories/files.
83 ///
Mike Stump1eb44332009-09-09 15:08:12 +000084 llvm::StringMap<DirectoryEntry> UniqueDirs;
Ted Kremenek6bb816a2008-02-24 03:15:25 +000085
86public:
Zhanyong Wan9b555ea2011-02-11 18:44:49 +000087 /// getDirectory - Return an existing DirectoryEntry with the given
88 /// name if there is already one; otherwise create and return a
89 /// default-constructed DirectoryEntry.
90 DirectoryEntry &getDirectory(const char *Name,
91 const struct stat & /*StatBuf*/) {
Ted Kremenek6bb816a2008-02-24 03:15:25 +000092 std::string FullPath(GetFullPath(Name));
Chris Lattnerf3e8a992010-11-23 20:30:42 +000093 return UniqueDirs.GetOrCreateValue(FullPath).getValue();
Ted Kremenek6bb816a2008-02-24 03:15:25 +000094 }
Mike Stump1eb44332009-09-09 15:08:12 +000095
Chris Lattnerf3e8a992010-11-23 20:30:42 +000096 size_t size() const { return UniqueDirs.size(); }
Ted Kremenek6bb816a2008-02-24 03:15:25 +000097};
98
99class FileManager::UniqueFileContainer {
100 /// UniqueFiles - Cache from full path to existing directories/files.
101 ///
Ted Kremenek75368892009-01-28 01:01:07 +0000102 llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000103
104public:
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000105 /// getFile - Return an existing FileEntry with the given name if
106 /// there is already one; otherwise create and return a
107 /// default-constructed FileEntry.
108 FileEntry &getFile(const char *Name, const struct stat & /*StatBuf*/) {
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000109 std::string FullPath(GetFullPath(Name));
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000110
Chris Lattnerc070da42010-08-23 23:50:42 +0000111 // LowercaseString because Windows filesystem is case insensitive.
112 FullPath = llvm::LowercaseString(FullPath);
Chris Lattnerf3e8a992010-11-23 20:30:42 +0000113 return UniqueFiles.GetOrCreateValue(FullPath).getValue();
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000114 }
115
Chris Lattnerf3e8a992010-11-23 20:30:42 +0000116 size_t size() const { return UniqueFiles.size(); }
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000117};
118
Ted Kremenekcb8d58b2009-01-28 00:27:31 +0000119//===----------------------------------------------------------------------===//
120// Unix-like Systems.
121//===----------------------------------------------------------------------===//
122
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000123#else
124
Benjamin Krameraa8b2d92010-11-21 11:32:22 +0000125#define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/')
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000126
127class FileManager::UniqueDirContainer {
128 /// UniqueDirs - Cache from ID's to existing directories/files.
Mike Stump1eb44332009-09-09 15:08:12 +0000129 std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000130
131public:
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000132 /// getDirectory - Return an existing DirectoryEntry with the given
133 /// ID's if there is already one; otherwise create and return a
134 /// default-constructed DirectoryEntry.
135 DirectoryEntry &getDirectory(const char * /*Name*/,
136 const struct stat &StatBuf) {
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000137 return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
138 }
139
Chris Lattnerf3e8a992010-11-23 20:30:42 +0000140 size_t size() const { return UniqueDirs.size(); }
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000141};
142
143class FileManager::UniqueFileContainer {
144 /// UniqueFiles - Cache from ID's to existing directories/files.
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000145 std::set<FileEntry> UniqueFiles;
146
147public:
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000148 /// getFile - Return an existing FileEntry with the given ID's if
149 /// there is already one; otherwise create and return a
150 /// default-constructed FileEntry.
151 FileEntry &getFile(const char * /*Name*/, const struct stat &StatBuf) {
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000152 return
153 const_cast<FileEntry&>(
154 *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
Ted Kremenek96438f32009-02-12 03:17:57 +0000155 StatBuf.st_ino,
156 StatBuf.st_mode)).first);
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000157 }
158
Chris Lattnerf3e8a992010-11-23 20:30:42 +0000159 size_t size() const { return UniqueFiles.size(); }
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000160};
161
162#endif
163
Ted Kremenekcb8d58b2009-01-28 00:27:31 +0000164//===----------------------------------------------------------------------===//
165// Common logic.
166//===----------------------------------------------------------------------===//
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000167
Chris Lattner7ad97ff2010-11-23 07:51:02 +0000168FileManager::FileManager(const FileSystemOptions &FSO)
169 : FileSystemOpts(FSO),
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000170 UniqueRealDirs(*new UniqueDirContainer()),
171 UniqueRealFiles(*new UniqueFileContainer()),
172 SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000173 NumDirLookups = NumFileLookups = 0;
174 NumDirCacheMisses = NumFileCacheMisses = 0;
175}
176
177FileManager::~FileManager() {
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000178 delete &UniqueRealDirs;
179 delete &UniqueRealFiles;
Chris Lattnerf3e8a992010-11-23 20:30:42 +0000180 for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
181 delete VirtualFileEntries[i];
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000182 for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
183 delete VirtualDirectoryEntries[i];
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000184}
185
Chris Lattner10e286a2010-11-23 19:19:34 +0000186void FileManager::addStatCache(FileSystemStatCache *statCache,
187 bool AtBeginning) {
Douglas Gregor52e71082009-10-16 18:18:30 +0000188 assert(statCache && "No stat cache provided?");
189 if (AtBeginning || StatCache.get() == 0) {
190 statCache->setNextStatCache(StatCache.take());
191 StatCache.reset(statCache);
192 return;
193 }
194
Chris Lattner10e286a2010-11-23 19:19:34 +0000195 FileSystemStatCache *LastCache = StatCache.get();
Douglas Gregor52e71082009-10-16 18:18:30 +0000196 while (LastCache->getNextStatCache())
197 LastCache = LastCache->getNextStatCache();
198
199 LastCache->setNextStatCache(statCache);
200}
201
Chris Lattner10e286a2010-11-23 19:19:34 +0000202void FileManager::removeStatCache(FileSystemStatCache *statCache) {
Douglas Gregor52e71082009-10-16 18:18:30 +0000203 if (!statCache)
204 return;
205
206 if (StatCache.get() == statCache) {
207 // This is the first stat cache.
208 StatCache.reset(StatCache->takeNextStatCache());
209 return;
210 }
211
212 // Find the stat cache in the list.
Chris Lattner10e286a2010-11-23 19:19:34 +0000213 FileSystemStatCache *PrevCache = StatCache.get();
Douglas Gregor52e71082009-10-16 18:18:30 +0000214 while (PrevCache && PrevCache->getNextStatCache() != statCache)
215 PrevCache = PrevCache->getNextStatCache();
Chris Lattnerf9f77662010-11-23 20:50:22 +0000216
217 assert(PrevCache && "Stat cache not found for removal");
218 PrevCache->setNextStatCache(statCache->getNextStatCache());
Douglas Gregor52e71082009-10-16 18:18:30 +0000219}
220
Douglas Gregor057e5672009-12-02 18:12:28 +0000221/// \brief Retrieve the directory that the given file name resides in.
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000222/// Filename can point to either a real file or a virtual file.
Douglas Gregor057e5672009-12-02 18:12:28 +0000223static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
Chris Lattner39b49bc2010-11-23 08:35:12 +0000224 llvm::StringRef Filename) {
Douglas Gregor057e5672009-12-02 18:12:28 +0000225 // Figure out what directory it is in. If the string contains a / in it,
226 // strip off everything after it.
227 // FIXME: this logic should be in sys::Path.
Benjamin Krameraa8b2d92010-11-21 11:32:22 +0000228 size_t SlashPos = Filename.size();
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000229 if (SlashPos == 0 || IS_DIR_SEPARATOR_CHAR(Filename[SlashPos-1]))
230 return NULL; // If Filename is empty or a directory.
231
Benjamin Krameraa8b2d92010-11-21 11:32:22 +0000232 while (SlashPos != 0 && !IS_DIR_SEPARATOR_CHAR(Filename[SlashPos-1]))
233 --SlashPos;
234
Chris Lattnerf69a1f32010-11-21 09:50:16 +0000235 // Use the current directory if file has no path component.
Benjamin Krameraa8b2d92010-11-21 11:32:22 +0000236 if (SlashPos == 0)
Chris Lattner39b49bc2010-11-23 08:35:12 +0000237 return FileMgr.getDirectory(".");
Douglas Gregor057e5672009-12-02 18:12:28 +0000238
Chris Lattnerf69a1f32010-11-21 09:50:16 +0000239 // Ignore repeated //'s.
Benjamin Krameraa8b2d92010-11-21 11:32:22 +0000240 while (SlashPos != 0 && IS_DIR_SEPARATOR_CHAR(Filename[SlashPos-1]))
Chris Lattnerf69a1f32010-11-21 09:50:16 +0000241 --SlashPos;
Benjamin Krameraa8b2d92010-11-21 11:32:22 +0000242
Chris Lattner39b49bc2010-11-23 08:35:12 +0000243 return FileMgr.getDirectory(Filename.substr(0, SlashPos));
Douglas Gregor057e5672009-12-02 18:12:28 +0000244}
245
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000246/// Add all ancestors of the given path (pointing to either a file or
247/// a directory) as virtual directories.
248void FileManager::addAncestorsAsVirtualDirs(llvm::StringRef Path) {
249 size_t SlashPos = Path.size();
250
251 // Find the beginning of the last segment in Path.
252 while (SlashPos != 0 && !IS_DIR_SEPARATOR_CHAR(Path[SlashPos-1]))
253 --SlashPos;
254
255 // Ignore repeated //'s.
256 while (SlashPos != 0 && IS_DIR_SEPARATOR_CHAR(Path[SlashPos-1]))
257 --SlashPos;
258
259 if (SlashPos == 0)
260 return;
261
262 llvm::StringRef DirName = Path.substr(0, SlashPos);
263 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
264 SeenDirEntries.GetOrCreateValue(DirName);
265
266 // When caching a virtual directory, we always cache its ancestors
267 // at the same time. Therefore, if DirName is already in the cache,
268 // we don't need to recurse as its ancestors must also already be in
269 // the cache.
270 if (NamedDirEnt.getValue())
271 return;
272
273 // Add the virtual directory to the cache.
274 DirectoryEntry *UDE = new DirectoryEntry;
275 UDE->Name = NamedDirEnt.getKeyData();
276 NamedDirEnt.setValue(UDE);
277 VirtualDirectoryEntries.push_back(UDE);
278
279 // Recursively add the other ancestors.
280 addAncestorsAsVirtualDirs(DirName);
281}
282
283/// getDirectory - Lookup, cache, and verify the specified directory
284/// (real or virtual). This returns NULL if the directory doesn't
285/// exist.
Mike Stump1eb44332009-09-09 15:08:12 +0000286///
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000287const DirectoryEntry *FileManager::getDirectory(llvm::StringRef DirName) {
John Thompson9a6ac542009-12-18 14:18:21 +0000288 // stat doesn't like trailing separators (at least on Windows).
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000289 if (DirName.size() > 1 && IS_DIR_SEPARATOR_CHAR(DirName.back()))
290 DirName = DirName.substr(0, DirName.size()-1);
John Thompson9a6ac542009-12-18 14:18:21 +0000291
Reid Spencer5f016e22007-07-11 17:01:13 +0000292 ++NumDirLookups;
293 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000294 SeenDirEntries.GetOrCreateValue(DirName);
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000296 // See if there was already an entry in the map. Note that the map
297 // contains both virtual and real directories.
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 if (NamedDirEnt.getValue())
Ted Kremenek3d2da3d2008-01-11 20:42:05 +0000299 return NamedDirEnt.getValue() == NON_EXISTENT_DIR
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 ? 0 : NamedDirEnt.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 ++NumDirCacheMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 // By default, initialize it to invalid.
Ted Kremenek3d2da3d2008-01-11 20:42:05 +0000305 NamedDirEnt.setValue(NON_EXISTENT_DIR);
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Reid Spencer5f016e22007-07-11 17:01:13 +0000307 // Get the null-terminated directory name as stored as the key of the
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000308 // SeenDirEntries map.
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 const char *InterndDirName = NamedDirEnt.getKeyData();
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 // Check to see if the directory exists.
312 struct stat StatBuf;
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000313 if (getStatValue(InterndDirName, StatBuf, 0/*directory lookup*/)) {
314 // There's no real directory at the given path.
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 return 0;
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000316 }
Ted Kremenek6bb816a2008-02-24 03:15:25 +0000317
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000318 // It exists. See if we have already opened a directory with the
319 // same inode (this occurs on Unix-like systems when one dir is
320 // symlinked to another, for example) or the same path (on
321 // Windows).
322 DirectoryEntry &UDE = UniqueRealDirs.getDirectory(InterndDirName, StatBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 NamedDirEnt.setValue(&UDE);
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000325 if (!UDE.getName()) {
326 // We don't have this directory yet, add it. We use the string
327 // key from the SeenDirEntries map as the string.
328 UDE.Name = InterndDirName;
329 }
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Reid Spencer5f016e22007-07-11 17:01:13 +0000331 return &UDE;
332}
333
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000334/// getFile - Lookup, cache, and verify the specified file (real or
335/// virtual). This returns NULL if the file doesn't exist.
Mike Stump1eb44332009-09-09 15:08:12 +0000336///
Chris Lattner39b49bc2010-11-23 08:35:12 +0000337const FileEntry *FileManager::getFile(llvm::StringRef Filename) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 ++NumFileLookups;
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 // See if there is already an entry in the map.
341 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000342 SeenFileEntries.GetOrCreateValue(Filename);
Reid Spencer5f016e22007-07-11 17:01:13 +0000343
344 // See if there is already an entry in the map.
345 if (NamedFileEnt.getValue())
Ted Kremenek3d2da3d2008-01-11 20:42:05 +0000346 return NamedFileEnt.getValue() == NON_EXISTENT_FILE
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 ? 0 : NamedFileEnt.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 ++NumFileCacheMisses;
350
351 // By default, initialize it to invalid.
Ted Kremenek3d2da3d2008-01-11 20:42:05 +0000352 NamedFileEnt.setValue(NON_EXISTENT_FILE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000353
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 // Get the null-terminated file name as stored as the key of the
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000355 // SeenFileEntries map.
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 const char *InterndFileName = NamedFileEnt.getKeyData();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Chris Lattnerf3e8a992010-11-23 20:30:42 +0000358 // Look up the directory for the file. When looking up something like
359 // sys/foo.h we'll discover all of the search directories that have a 'sys'
360 // subdirectory. This will let us avoid having to waste time on known-to-fail
361 // searches when we go to find sys/bar.h, because all the search directories
362 // without a 'sys' subdir will get a cached failure result.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000363 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename);
Douglas Gregor057e5672009-12-02 18:12:28 +0000364 if (DirInfo == 0) // Directory doesn't exist, file can't exist.
365 return 0;
366
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 // FIXME: Use the directory info to prune this, before doing the stat syscall.
368 // FIXME: This will reduce the # syscalls.
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 // Nope, there isn't. Check to see if the file exists.
Chris Lattner898a0612010-11-23 21:17:56 +0000371 int FileDescriptor = -1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 struct stat StatBuf;
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000373 if (getStatValue(InterndFileName, StatBuf, &FileDescriptor)) {
374 // There's no real file at the given path.
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 return 0;
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000376 }
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Ted Kremenekbca6d122007-12-18 22:29:39 +0000378 // It exists. See if we have already opened a file with the same inode.
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 // This occurs when one dir is symlinked to another, for example.
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000380 FileEntry &UFE = UniqueRealFiles.getFile(InterndFileName, StatBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 NamedFileEnt.setValue(&UFE);
Chris Lattner898a0612010-11-23 21:17:56 +0000383 if (UFE.getName()) { // Already have an entry with this inode, return it.
384 // If the stat process opened the file, close it to avoid a FD leak.
385 if (FileDescriptor != -1)
386 close(FileDescriptor);
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000387
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 return &UFE;
Chris Lattner898a0612010-11-23 21:17:56 +0000389 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000390
391 // Otherwise, we don't have this directory yet, add it.
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000392 // FIXME: Change the name to be a char* that points back to the
393 // 'SeenFileEntries' key.
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 UFE.Name = InterndFileName;
395 UFE.Size = StatBuf.st_size;
396 UFE.ModTime = StatBuf.st_mtime;
397 UFE.Dir = DirInfo;
398 UFE.UID = NextFileUID++;
Chris Lattner898a0612010-11-23 21:17:56 +0000399 UFE.FD = FileDescriptor;
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 return &UFE;
401}
402
Douglas Gregor057e5672009-12-02 18:12:28 +0000403const FileEntry *
Benjamin Kramerec1b1cc2010-07-14 23:19:41 +0000404FileManager::getVirtualFile(llvm::StringRef Filename, off_t Size,
Chris Lattner39b49bc2010-11-23 08:35:12 +0000405 time_t ModificationTime) {
Douglas Gregor057e5672009-12-02 18:12:28 +0000406 ++NumFileLookups;
407
408 // See if there is already an entry in the map.
409 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000410 SeenFileEntries.GetOrCreateValue(Filename);
Douglas Gregor057e5672009-12-02 18:12:28 +0000411
412 // See if there is already an entry in the map.
Axel Naumann04331162011-01-27 10:55:51 +0000413 if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
414 return NamedFileEnt.getValue();
Douglas Gregor057e5672009-12-02 18:12:28 +0000415
416 ++NumFileCacheMisses;
417
418 // By default, initialize it to invalid.
419 NamedFileEnt.setValue(NON_EXISTENT_FILE);
420
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000421 addAncestorsAsVirtualDirs(Filename);
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000422 FileEntry *UFE = 0;
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000423
424 // Now that all ancestors of Filename are in the cache, the
425 // following call is guaranteed to find the DirectoryEntry from the
426 // cache.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000427 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename);
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000428 assert(DirInfo &&
429 "The directory of a virtual file should already be in the cache.");
Douglas Gregor057e5672009-12-02 18:12:28 +0000430
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000431 // Check to see if the file exists. If so, drop the virtual file
432 int FileDescriptor = -1;
433 struct stat StatBuf;
434 const char *InterndFileName = NamedFileEnt.getKeyData();
435 if (getStatValue(InterndFileName, StatBuf, &FileDescriptor) == 0) {
436 // If the stat process opened the file, close it to avoid a FD leak.
437 if (FileDescriptor != -1)
438 close(FileDescriptor);
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000439
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000440 StatBuf.st_size = Size;
441 StatBuf.st_mtime = ModificationTime;
442 UFE = &UniqueRealFiles.getFile(InterndFileName, StatBuf);
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000443
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000444 NamedFileEnt.setValue(UFE);
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000445
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000446 // If we had already opened this file, close it now so we don't
447 // leak the descriptor. We're not going to use the file
448 // descriptor anyway, since this is a virtual file.
449 if (UFE->FD != -1) {
450 close(UFE->FD);
451 UFE->FD = -1;
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000452 }
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000453
454 // If we already have an entry with this inode, return it.
455 if (UFE->getName())
456 return UFE;
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000457 }
458
459 if (!UFE) {
460 UFE = new FileEntry();
461 VirtualFileEntries.push_back(UFE);
462 NamedFileEnt.setValue(UFE);
463 }
Douglas Gregor057e5672009-12-02 18:12:28 +0000464
Chris Lattnerf9f77662010-11-23 20:50:22 +0000465 UFE->Name = InterndFileName;
Douglas Gregor057e5672009-12-02 18:12:28 +0000466 UFE->Size = Size;
467 UFE->ModTime = ModificationTime;
468 UFE->Dir = DirInfo;
469 UFE->UID = NextFileUID++;
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000470 UFE->FD = -1;
Douglas Gregor057e5672009-12-02 18:12:28 +0000471 return UFE;
472}
473
Chris Lattner67452f52010-11-23 04:45:28 +0000474void FileManager::FixupRelativePath(llvm::sys::Path &path,
475 const FileSystemOptions &FSOpts) {
Michael J. Spencer256053b2010-12-17 21:22:22 +0000476 if (FSOpts.WorkingDir.empty() || llvm::sys::path::is_absolute(path.str()))
477 return;
478
479 llvm::SmallString<128> NewPath(FSOpts.WorkingDir);
480 llvm::sys::path::append(NewPath, path.str());
Chris Lattner67452f52010-11-23 04:45:28 +0000481 path = NewPath;
482}
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000483
Chris Lattner67452f52010-11-23 04:45:28 +0000484llvm::MemoryBuffer *FileManager::
Chris Lattner75dfb652010-11-23 09:19:42 +0000485getBufferForFile(const FileEntry *Entry, std::string *ErrorStr) {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000486 llvm::OwningPtr<llvm::MemoryBuffer> Result;
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000487 llvm::error_code ec;
Chris Lattner5cc1c732010-11-23 22:32:37 +0000488 if (FileSystemOpts.WorkingDir.empty()) {
489 const char *Filename = Entry->getName();
490 // If the file is already open, use the open file descriptor.
491 if (Entry->FD != -1) {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000492 ec = llvm::MemoryBuffer::getOpenFile(Entry->FD, Filename, Result,
493 Entry->getSize());
494 if (ErrorStr)
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000495 *ErrorStr = ec.message();
Rafael Espindola100f2392011-02-08 22:44:16 +0000496
497 close(Entry->FD);
Chris Lattner5cc1c732010-11-23 22:32:37 +0000498 Entry->FD = -1;
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000499 return Result.take();
Chris Lattner5cc1c732010-11-23 22:32:37 +0000500 }
501
502 // Otherwise, open the file.
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000503 ec = llvm::MemoryBuffer::getFile(Filename, Result, Entry->getSize());
504 if (ec && ErrorStr)
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000505 *ErrorStr = ec.message();
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000506 return Result.take();
Chris Lattner5cc1c732010-11-23 22:32:37 +0000507 }
Chris Lattner67452f52010-11-23 04:45:28 +0000508
Chris Lattner5cc1c732010-11-23 22:32:37 +0000509 llvm::sys::Path FilePath(Entry->getName());
Chris Lattner67452f52010-11-23 04:45:28 +0000510 FixupRelativePath(FilePath, FileSystemOpts);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000511 ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result, Entry->getSize());
512 if (ec && ErrorStr)
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000513 *ErrorStr = ec.message();
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000514 return Result.take();
Chris Lattner75dfb652010-11-23 09:19:42 +0000515}
516
517llvm::MemoryBuffer *FileManager::
518getBufferForFile(llvm::StringRef Filename, std::string *ErrorStr) {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000519 llvm::OwningPtr<llvm::MemoryBuffer> Result;
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000520 llvm::error_code ec;
521 if (FileSystemOpts.WorkingDir.empty()) {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000522 ec = llvm::MemoryBuffer::getFile(Filename, Result);
523 if (ec && ErrorStr)
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000524 *ErrorStr = ec.message();
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000525 return Result.take();
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000526 }
527
Chris Lattner75dfb652010-11-23 09:19:42 +0000528 llvm::sys::Path FilePath(Filename);
529 FixupRelativePath(FilePath, FileSystemOpts);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000530 ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result);
531 if (ec && ErrorStr)
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000532 *ErrorStr = ec.message();
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000533 return Result.take();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000534}
535
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000536/// getStatValue - Get the 'stat' information for the specified path,
537/// using the cache to accelerate it if possible. This returns true
538/// if the path points to a virtual file or does not exist, or returns
539/// false if it's an existent real file. If FileDescriptor is NULL,
540/// do directory look-up instead of file look-up.
Chris Lattnerf9f77662010-11-23 20:50:22 +0000541bool FileManager::getStatValue(const char *Path, struct stat &StatBuf,
Chris Lattner898a0612010-11-23 21:17:56 +0000542 int *FileDescriptor) {
Chris Lattner10e286a2010-11-23 19:19:34 +0000543 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
544 // absolute!
Chris Lattner11aa4b02010-11-23 19:56:39 +0000545 if (FileSystemOpts.WorkingDir.empty())
Chris Lattner898a0612010-11-23 21:17:56 +0000546 return FileSystemStatCache::get(Path, StatBuf, FileDescriptor,
547 StatCache.get());
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000548
Chris Lattner10e286a2010-11-23 19:19:34 +0000549 llvm::sys::Path FilePath(Path);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000550 FixupRelativePath(FilePath, FileSystemOpts);
Chris Lattner11aa4b02010-11-23 19:56:39 +0000551
Chris Lattner898a0612010-11-23 21:17:56 +0000552 return FileSystemStatCache::get(FilePath.c_str(), StatBuf, FileDescriptor,
553 StatCache.get());
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000554}
555
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000556void FileManager::GetUniqueIDMapping(
557 llvm::SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
558 UIDToFiles.clear();
559 UIDToFiles.resize(NextFileUID);
560
561 // Map file entries
562 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000563 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
Douglas Gregorcfbf1c72011-02-10 17:09:37 +0000564 FE != FEEnd; ++FE)
565 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
566 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
567
568 // Map virtual file entries
569 for (llvm::SmallVector<FileEntry*, 4>::const_iterator
570 VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
571 VFE != VFEEnd; ++VFE)
572 if (*VFE && *VFE != NON_EXISTENT_FILE)
573 UIDToFiles[(*VFE)->getUID()] = *VFE;
574}
Chris Lattner10e286a2010-11-23 19:19:34 +0000575
576
Reid Spencer5f016e22007-07-11 17:01:13 +0000577void FileManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000578 llvm::errs() << "\n*** File Manager Stats:\n";
Zhanyong Wan9b555ea2011-02-11 18:44:49 +0000579 llvm::errs() << UniqueRealFiles.size() << " real files found, "
580 << UniqueRealDirs.size() << " real dirs found.\n";
581 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
582 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000583 llvm::errs() << NumDirLookups << " dir lookups, "
584 << NumDirCacheMisses << " dir cache misses.\n";
585 llvm::errs() << NumFileLookups << " file lookups, "
586 << NumFileCacheMisses << " file cache misses.\n";
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000588 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
Reid Spencer5f016e22007-07-11 17:01:13 +0000589}