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