1 //===--- FileManager.cpp - File System Probing and Caching ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
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"
21 #include "clang/Basic/FileSystemStatCache.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/system_error.h"
29 #include "llvm/Config/config.h"
30 #include <map>
31 #include <set>
32 #include <string>
33
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
41 using namespace clang;
42
43 // FIXME: Enhance libsystem to support inode and other fields.
44 #include <sys/stat.h>
45
46 /// NON_EXISTENT_DIR - A special value distinct from null that is used to
47 /// represent a dir name that doesn't exist on the disk.
48 #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)
49
50 /// 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
~FileEntry()55 FileEntry::~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
61 //===----------------------------------------------------------------------===//
62 // Windows.
63 //===----------------------------------------------------------------------===//
64
65 #ifdef LLVM_ON_WIN32
66
67 namespace {
GetFullPath(const char * relPath)68 static std::string GetFullPath(const char *relPath) {
69 char *absPathStrPtr = _fullpath(NULL, relPath, 0);
70 assert(absPathStrPtr && "_fullpath() returned NULL!");
71
72 std::string absPath(absPathStrPtr);
73
74 free(absPathStrPtr);
75 return absPath;
76 }
77 }
78
79 class FileManager::UniqueDirContainer {
80 /// UniqueDirs - Cache from full path to existing directories/files.
81 ///
82 llvm::StringMap<DirectoryEntry> UniqueDirs;
83
84 public:
85 /// getDirectory - Return an existing DirectoryEntry with the given
86 /// name if there is already one; otherwise create and return a
87 /// default-constructed DirectoryEntry.
getDirectory(const char * Name,const struct stat &)88 DirectoryEntry &getDirectory(const char *Name,
89 const struct stat & /*StatBuf*/) {
90 std::string FullPath(GetFullPath(Name));
91 return UniqueDirs.GetOrCreateValue(FullPath).getValue();
92 }
93
size() const94 size_t size() const { return UniqueDirs.size(); }
95 };
96
97 class FileManager::UniqueFileContainer {
98 /// UniqueFiles - Cache from full path to existing directories/files.
99 ///
100 llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;
101
102 public:
103 /// getFile - Return an existing FileEntry with the given name if
104 /// there is already one; otherwise create and return a
105 /// default-constructed FileEntry.
getFile(const char * Name,const struct stat &)106 FileEntry &getFile(const char *Name, const struct stat & /*StatBuf*/) {
107 std::string FullPath(GetFullPath(Name));
108
109 // LowercaseString because Windows filesystem is case insensitive.
110 FullPath = llvm::LowercaseString(FullPath);
111 return UniqueFiles.GetOrCreateValue(FullPath).getValue();
112 }
113
size() const114 size_t size() const { return UniqueFiles.size(); }
115 };
116
117 //===----------------------------------------------------------------------===//
118 // Unix-like Systems.
119 //===----------------------------------------------------------------------===//
120
121 #else
122
123 class FileManager::UniqueDirContainer {
124 /// UniqueDirs - Cache from ID's to existing directories/files.
125 std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;
126
127 public:
128 /// getDirectory - Return an existing DirectoryEntry with the given
129 /// ID's if there is already one; otherwise create and return a
130 /// default-constructed DirectoryEntry.
getDirectory(const char *,const struct stat & StatBuf)131 DirectoryEntry &getDirectory(const char * /*Name*/,
132 const struct stat &StatBuf) {
133 return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
134 }
135
size() const136 size_t size() const { return UniqueDirs.size(); }
137 };
138
139 class FileManager::UniqueFileContainer {
140 /// UniqueFiles - Cache from ID's to existing directories/files.
141 std::set<FileEntry> UniqueFiles;
142
143 public:
144 /// getFile - Return an existing FileEntry with the given ID's if
145 /// there is already one; otherwise create and return a
146 /// default-constructed FileEntry.
getFile(const char *,const struct stat & StatBuf)147 FileEntry &getFile(const char * /*Name*/, const struct stat &StatBuf) {
148 return
149 const_cast<FileEntry&>(
150 *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
151 StatBuf.st_ino,
152 StatBuf.st_mode)).first);
153 }
154
size() const155 size_t size() const { return UniqueFiles.size(); }
156 };
157
158 #endif
159
160 //===----------------------------------------------------------------------===//
161 // Common logic.
162 //===----------------------------------------------------------------------===//
163
FileManager(const FileSystemOptions & FSO)164 FileManager::FileManager(const FileSystemOptions &FSO)
165 : FileSystemOpts(FSO),
166 UniqueRealDirs(*new UniqueDirContainer()),
167 UniqueRealFiles(*new UniqueFileContainer()),
168 SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) {
169 NumDirLookups = NumFileLookups = 0;
170 NumDirCacheMisses = NumFileCacheMisses = 0;
171 }
172
~FileManager()173 FileManager::~FileManager() {
174 delete &UniqueRealDirs;
175 delete &UniqueRealFiles;
176 for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i)
177 delete VirtualFileEntries[i];
178 for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i)
179 delete VirtualDirectoryEntries[i];
180 }
181
addStatCache(FileSystemStatCache * statCache,bool AtBeginning)182 void FileManager::addStatCache(FileSystemStatCache *statCache,
183 bool AtBeginning) {
184 assert(statCache && "No stat cache provided?");
185 if (AtBeginning || StatCache.get() == 0) {
186 statCache->setNextStatCache(StatCache.take());
187 StatCache.reset(statCache);
188 return;
189 }
190
191 FileSystemStatCache *LastCache = StatCache.get();
192 while (LastCache->getNextStatCache())
193 LastCache = LastCache->getNextStatCache();
194
195 LastCache->setNextStatCache(statCache);
196 }
197
removeStatCache(FileSystemStatCache * statCache)198 void FileManager::removeStatCache(FileSystemStatCache *statCache) {
199 if (!statCache)
200 return;
201
202 if (StatCache.get() == statCache) {
203 // This is the first stat cache.
204 StatCache.reset(StatCache->takeNextStatCache());
205 return;
206 }
207
208 // Find the stat cache in the list.
209 FileSystemStatCache *PrevCache = StatCache.get();
210 while (PrevCache && PrevCache->getNextStatCache() != statCache)
211 PrevCache = PrevCache->getNextStatCache();
212
213 assert(PrevCache && "Stat cache not found for removal");
214 PrevCache->setNextStatCache(statCache->getNextStatCache());
215 }
216
217 /// \brief Retrieve the directory that the given file name resides in.
218 /// Filename can point to either a real file or a virtual file.
getDirectoryFromFile(FileManager & FileMgr,llvm::StringRef Filename)219 static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
220 llvm::StringRef Filename) {
221 if (Filename.empty())
222 return NULL;
223
224 if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
225 return NULL; // If Filename is a directory.
226
227 llvm::StringRef DirName = llvm::sys::path::parent_path(Filename);
228 // Use the current directory if file has no path component.
229 if (DirName.empty())
230 DirName = ".";
231
232 return FileMgr.getDirectory(DirName);
233 }
234
235 /// Add all ancestors of the given path (pointing to either a file or
236 /// a directory) as virtual directories.
addAncestorsAsVirtualDirs(llvm::StringRef Path)237 void FileManager::addAncestorsAsVirtualDirs(llvm::StringRef Path) {
238 llvm::StringRef DirName = llvm::sys::path::parent_path(Path);
239 if (DirName.empty())
240 return;
241
242 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
243 SeenDirEntries.GetOrCreateValue(DirName);
244
245 // When caching a virtual directory, we always cache its ancestors
246 // at the same time. Therefore, if DirName is already in the cache,
247 // we don't need to recurse as its ancestors must also already be in
248 // the cache.
249 if (NamedDirEnt.getValue())
250 return;
251
252 // Add the virtual directory to the cache.
253 DirectoryEntry *UDE = new DirectoryEntry;
254 UDE->Name = NamedDirEnt.getKeyData();
255 NamedDirEnt.setValue(UDE);
256 VirtualDirectoryEntries.push_back(UDE);
257
258 // Recursively add the other ancestors.
259 addAncestorsAsVirtualDirs(DirName);
260 }
261
262 /// getDirectory - Lookup, cache, and verify the specified directory
263 /// (real or virtual). This returns NULL if the directory doesn't
264 /// exist.
265 ///
getDirectory(llvm::StringRef DirName)266 const DirectoryEntry *FileManager::getDirectory(llvm::StringRef DirName) {
267 ++NumDirLookups;
268 llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
269 SeenDirEntries.GetOrCreateValue(DirName);
270
271 // See if there was already an entry in the map. Note that the map
272 // contains both virtual and real directories.
273 if (NamedDirEnt.getValue())
274 return NamedDirEnt.getValue() == NON_EXISTENT_DIR
275 ? 0 : NamedDirEnt.getValue();
276
277 ++NumDirCacheMisses;
278
279 // By default, initialize it to invalid.
280 NamedDirEnt.setValue(NON_EXISTENT_DIR);
281
282 // Get the null-terminated directory name as stored as the key of the
283 // SeenDirEntries map.
284 const char *InterndDirName = NamedDirEnt.getKeyData();
285
286 // Check to see if the directory exists.
287 struct stat StatBuf;
288 if (getStatValue(InterndDirName, StatBuf, 0/*directory lookup*/)) {
289 // There's no real directory at the given path.
290 return 0;
291 }
292
293 // It exists. See if we have already opened a directory with the
294 // same inode (this occurs on Unix-like systems when one dir is
295 // symlinked to another, for example) or the same path (on
296 // Windows).
297 DirectoryEntry &UDE = UniqueRealDirs.getDirectory(InterndDirName, StatBuf);
298
299 NamedDirEnt.setValue(&UDE);
300 if (!UDE.getName()) {
301 // We don't have this directory yet, add it. We use the string
302 // key from the SeenDirEntries map as the string.
303 UDE.Name = InterndDirName;
304 }
305
306 return &UDE;
307 }
308
309 /// getFile - Lookup, cache, and verify the specified file (real or
310 /// virtual). This returns NULL if the file doesn't exist.
311 ///
getFile(llvm::StringRef Filename,bool openFile)312 const FileEntry *FileManager::getFile(llvm::StringRef Filename, bool openFile) {
313 ++NumFileLookups;
314
315 // See if there is already an entry in the map.
316 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
317 SeenFileEntries.GetOrCreateValue(Filename);
318
319 // See if there is already an entry in the map.
320 if (NamedFileEnt.getValue())
321 return NamedFileEnt.getValue() == NON_EXISTENT_FILE
322 ? 0 : NamedFileEnt.getValue();
323
324 ++NumFileCacheMisses;
325
326 // By default, initialize it to invalid.
327 NamedFileEnt.setValue(NON_EXISTENT_FILE);
328
329 // Get the null-terminated file name as stored as the key of the
330 // SeenFileEntries map.
331 const char *InterndFileName = NamedFileEnt.getKeyData();
332
333 // Look up the directory for the file. When looking up something like
334 // sys/foo.h we'll discover all of the search directories that have a 'sys'
335 // subdirectory. This will let us avoid having to waste time on known-to-fail
336 // searches when we go to find sys/bar.h, because all the search directories
337 // without a 'sys' subdir will get a cached failure result.
338 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename);
339 if (DirInfo == 0) // Directory doesn't exist, file can't exist.
340 return 0;
341
342 // FIXME: Use the directory info to prune this, before doing the stat syscall.
343 // FIXME: This will reduce the # syscalls.
344
345 // Nope, there isn't. Check to see if the file exists.
346 int FileDescriptor = -1;
347 struct stat StatBuf;
348 if (getStatValue(InterndFileName, StatBuf, &FileDescriptor)) {
349 // There's no real file at the given path.
350 return 0;
351 }
352
353 if (FileDescriptor != -1 && !openFile) {
354 close(FileDescriptor);
355 FileDescriptor = -1;
356 }
357
358 // It exists. See if we have already opened a file with the same inode.
359 // This occurs when one dir is symlinked to another, for example.
360 FileEntry &UFE = UniqueRealFiles.getFile(InterndFileName, StatBuf);
361
362 NamedFileEnt.setValue(&UFE);
363 if (UFE.getName()) { // Already have an entry with this inode, return it.
364 // If the stat process opened the file, close it to avoid a FD leak.
365 if (FileDescriptor != -1)
366 close(FileDescriptor);
367
368 return &UFE;
369 }
370
371 // Otherwise, we don't have this directory yet, add it.
372 // FIXME: Change the name to be a char* that points back to the
373 // 'SeenFileEntries' key.
374 UFE.Name = InterndFileName;
375 UFE.Size = StatBuf.st_size;
376 UFE.ModTime = StatBuf.st_mtime;
377 UFE.Dir = DirInfo;
378 UFE.UID = NextFileUID++;
379 UFE.FD = FileDescriptor;
380 return &UFE;
381 }
382
383 const FileEntry *
getVirtualFile(llvm::StringRef Filename,off_t Size,time_t ModificationTime)384 FileManager::getVirtualFile(llvm::StringRef Filename, off_t Size,
385 time_t ModificationTime) {
386 ++NumFileLookups;
387
388 // See if there is already an entry in the map.
389 llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
390 SeenFileEntries.GetOrCreateValue(Filename);
391
392 // See if there is already an entry in the map.
393 if (NamedFileEnt.getValue() && NamedFileEnt.getValue() != NON_EXISTENT_FILE)
394 return NamedFileEnt.getValue();
395
396 ++NumFileCacheMisses;
397
398 // By default, initialize it to invalid.
399 NamedFileEnt.setValue(NON_EXISTENT_FILE);
400
401 addAncestorsAsVirtualDirs(Filename);
402 FileEntry *UFE = 0;
403
404 // Now that all ancestors of Filename are in the cache, the
405 // following call is guaranteed to find the DirectoryEntry from the
406 // cache.
407 const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename);
408 assert(DirInfo &&
409 "The directory of a virtual file should already be in the cache.");
410
411 // Check to see if the file exists. If so, drop the virtual file
412 int FileDescriptor = -1;
413 struct stat StatBuf;
414 const char *InterndFileName = NamedFileEnt.getKeyData();
415 if (getStatValue(InterndFileName, StatBuf, &FileDescriptor) == 0) {
416 // If the stat process opened the file, close it to avoid a FD leak.
417 if (FileDescriptor != -1)
418 close(FileDescriptor);
419
420 StatBuf.st_size = Size;
421 StatBuf.st_mtime = ModificationTime;
422 UFE = &UniqueRealFiles.getFile(InterndFileName, StatBuf);
423
424 NamedFileEnt.setValue(UFE);
425
426 // If we had already opened this file, close it now so we don't
427 // leak the descriptor. We're not going to use the file
428 // descriptor anyway, since this is a virtual file.
429 if (UFE->FD != -1) {
430 close(UFE->FD);
431 UFE->FD = -1;
432 }
433
434 // If we already have an entry with this inode, return it.
435 if (UFE->getName())
436 return UFE;
437 }
438
439 if (!UFE) {
440 UFE = new FileEntry();
441 VirtualFileEntries.push_back(UFE);
442 NamedFileEnt.setValue(UFE);
443 }
444
445 UFE->Name = InterndFileName;
446 UFE->Size = Size;
447 UFE->ModTime = ModificationTime;
448 UFE->Dir = DirInfo;
449 UFE->UID = NextFileUID++;
450 UFE->FD = -1;
451 return UFE;
452 }
453
FixupRelativePath(llvm::SmallVectorImpl<char> & path) const454 void FileManager::FixupRelativePath(llvm::SmallVectorImpl<char> &path) const {
455 llvm::StringRef pathRef(path.data(), path.size());
456
457 if (FileSystemOpts.WorkingDir.empty()
458 || llvm::sys::path::is_absolute(pathRef))
459 return;
460
461 llvm::SmallString<128> NewPath(FileSystemOpts.WorkingDir);
462 llvm::sys::path::append(NewPath, pathRef);
463 path = NewPath;
464 }
465
466 llvm::MemoryBuffer *FileManager::
getBufferForFile(const FileEntry * Entry,std::string * ErrorStr)467 getBufferForFile(const FileEntry *Entry, std::string *ErrorStr) {
468 llvm::OwningPtr<llvm::MemoryBuffer> Result;
469 llvm::error_code ec;
470
471 const char *Filename = Entry->getName();
472 // If the file is already open, use the open file descriptor.
473 if (Entry->FD != -1) {
474 ec = llvm::MemoryBuffer::getOpenFile(Entry->FD, Filename, Result,
475 Entry->getSize());
476 if (ErrorStr)
477 *ErrorStr = ec.message();
478
479 close(Entry->FD);
480 Entry->FD = -1;
481 return Result.take();
482 }
483
484 // Otherwise, open the file.
485
486 if (FileSystemOpts.WorkingDir.empty()) {
487 ec = llvm::MemoryBuffer::getFile(Filename, Result, Entry->getSize());
488 if (ec && ErrorStr)
489 *ErrorStr = ec.message();
490 return Result.take();
491 }
492
493 llvm::SmallString<128> FilePath(Entry->getName());
494 FixupRelativePath(FilePath);
495 ec = llvm::MemoryBuffer::getFile(FilePath.str(), Result, Entry->getSize());
496 if (ec && ErrorStr)
497 *ErrorStr = ec.message();
498 return Result.take();
499 }
500
501 llvm::MemoryBuffer *FileManager::
getBufferForFile(llvm::StringRef Filename,std::string * ErrorStr)502 getBufferForFile(llvm::StringRef Filename, std::string *ErrorStr) {
503 llvm::OwningPtr<llvm::MemoryBuffer> Result;
504 llvm::error_code ec;
505 if (FileSystemOpts.WorkingDir.empty()) {
506 ec = llvm::MemoryBuffer::getFile(Filename, Result);
507 if (ec && ErrorStr)
508 *ErrorStr = ec.message();
509 return Result.take();
510 }
511
512 llvm::SmallString<128> FilePath(Filename);
513 FixupRelativePath(FilePath);
514 ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result);
515 if (ec && ErrorStr)
516 *ErrorStr = ec.message();
517 return Result.take();
518 }
519
520 /// getStatValue - Get the 'stat' information for the specified path,
521 /// using the cache to accelerate it if possible. This returns true
522 /// if the path points to a virtual file or does not exist, or returns
523 /// false if it's an existent real file. If FileDescriptor is NULL,
524 /// do directory look-up instead of file look-up.
getStatValue(const char * Path,struct stat & StatBuf,int * FileDescriptor)525 bool FileManager::getStatValue(const char *Path, struct stat &StatBuf,
526 int *FileDescriptor) {
527 // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
528 // absolute!
529 if (FileSystemOpts.WorkingDir.empty())
530 return FileSystemStatCache::get(Path, StatBuf, FileDescriptor,
531 StatCache.get());
532
533 llvm::SmallString<128> FilePath(Path);
534 FixupRelativePath(FilePath);
535
536 return FileSystemStatCache::get(FilePath.c_str(), StatBuf, FileDescriptor,
537 StatCache.get());
538 }
539
getNoncachedStatValue(llvm::StringRef Path,struct stat & StatBuf)540 bool FileManager::getNoncachedStatValue(llvm::StringRef Path,
541 struct stat &StatBuf) {
542 llvm::SmallString<128> FilePath(Path);
543 FixupRelativePath(FilePath);
544
545 return ::stat(FilePath.c_str(), &StatBuf) != 0;
546 }
547
GetUniqueIDMapping(llvm::SmallVectorImpl<const FileEntry * > & UIDToFiles) const548 void FileManager::GetUniqueIDMapping(
549 llvm::SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
550 UIDToFiles.clear();
551 UIDToFiles.resize(NextFileUID);
552
553 // Map file entries
554 for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator
555 FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end();
556 FE != FEEnd; ++FE)
557 if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE)
558 UIDToFiles[FE->getValue()->getUID()] = FE->getValue();
559
560 // Map virtual file entries
561 for (llvm::SmallVector<FileEntry*, 4>::const_iterator
562 VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end();
563 VFE != VFEEnd; ++VFE)
564 if (*VFE && *VFE != NON_EXISTENT_FILE)
565 UIDToFiles[(*VFE)->getUID()] = *VFE;
566 }
567
568
PrintStats() const569 void FileManager::PrintStats() const {
570 llvm::errs() << "\n*** File Manager Stats:\n";
571 llvm::errs() << UniqueRealFiles.size() << " real files found, "
572 << UniqueRealDirs.size() << " real dirs found.\n";
573 llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
574 << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
575 llvm::errs() << NumDirLookups << " dir lookups, "
576 << NumDirCacheMisses << " dir cache misses.\n";
577 llvm::errs() << NumFileLookups << " file lookups, "
578 << NumFileCacheMisses << " file cache misses.\n";
579
580 //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
581 }
582