Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Basic/FileManager.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- FileManager.cpp - File System Probing and Caching ----------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements the FileManager interface.
10
//
11
//===----------------------------------------------------------------------===//
12
//
13
// TODO: This should index all interesting directories with dirent calls.
14
//  getdirentries ?
15
//  opendir/readdir_r/closedir ?
16
//
17
//===----------------------------------------------------------------------===//
18
19
#include "clang/Basic/FileManager.h"
20
#include "clang/Basic/FileSystemStatCache.h"
21
#include "llvm/ADT/STLExtras.h"
22
#include "llvm/ADT/SmallString.h"
23
#include "llvm/ADT/Statistic.h"
24
#include "llvm/Config/llvm-config.h"
25
#include "llvm/Support/FileSystem.h"
26
#include "llvm/Support/MemoryBuffer.h"
27
#include "llvm/Support/Path.h"
28
#include "llvm/Support/raw_ostream.h"
29
#include <algorithm>
30
#include <cassert>
31
#include <climits>
32
#include <cstdint>
33
#include <cstdlib>
34
#include <string>
35
#include <utility>
36
37
using namespace clang;
38
39
#define DEBUG_TYPE "file-search"
40
41
ALWAYS_ENABLED_STATISTIC(NumDirLookups, "Number of directory lookups.");
42
ALWAYS_ENABLED_STATISTIC(NumFileLookups, "Number of file lookups.");
43
ALWAYS_ENABLED_STATISTIC(NumDirCacheMisses,
44
                         "Number of directory cache misses.");
45
ALWAYS_ENABLED_STATISTIC(NumFileCacheMisses, "Number of file cache misses.");
46
47
//===----------------------------------------------------------------------===//
48
// Common logic.
49
//===----------------------------------------------------------------------===//
50
51
FileManager::FileManager(const FileSystemOptions &FSO,
52
                         IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
53
    : FS(std::move(FS)), FileSystemOpts(FSO), SeenDirEntries(64),
54
146k
      SeenFileEntries(64), NextFileUID(0) {
55
146k
  // If the caller doesn't provide a virtual file system, just grab the real
56
146k
  // file system.
57
146k
  if (!this->FS)
58
285
    this->FS = llvm::vfs::getRealFileSystem();
59
146k
}
60
61
138k
FileManager::~FileManager() = default;
62
63
12
void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
64
12
  assert(statCache && "No stat cache provided?");
65
12
  StatCache = std::move(statCache);
66
12
}
67
68
3.76k
void FileManager::clearStatCache() { StatCache.reset(); }
69
70
/// Retrieve the directory that the given file name resides in.
71
/// Filename can point to either a real file or a virtual file.
72
static llvm::ErrorOr<const DirectoryEntry *>
73
getDirectoryFromFile(FileManager &FileMgr, StringRef Filename,
74
5.79M
                     bool CacheFailure) {
75
5.79M
  if (Filename.empty())
76
0
    return std::errc::no_such_file_or_directory;
77
5.79M
78
5.79M
  if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
79
20
    return std::errc::is_a_directory;
80
5.79M
81
5.79M
  StringRef DirName = llvm::sys::path::parent_path(Filename);
82
5.79M
  // Use the current directory if file has no path component.
83
5.79M
  if (DirName.empty())
84
58.8k
    DirName = ".";
85
5.79M
86
5.79M
  return FileMgr.getDirectory(DirName, CacheFailure);
87
5.79M
}
88
89
/// Add all ancestors of the given path (pointing to either a file or
90
/// a directory) as virtual directories.
91
9.38k
void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
92
9.38k
  StringRef DirName = llvm::sys::path::parent_path(Path);
93
9.38k
  if (DirName.empty())
94
4.52k
    DirName = ".";
95
9.38k
96
9.38k
  auto &NamedDirEnt = *SeenDirEntries.insert(
97
9.38k
        {DirName, std::errc::no_such_file_or_directory}).first;
98
9.38k
99
9.38k
  // When caching a virtual directory, we always cache its ancestors
100
9.38k
  // at the same time.  Therefore, if DirName is already in the cache,
101
9.38k
  // we don't need to recurse as its ancestors must also already be in
102
9.38k
  // the cache (or it's a known non-virtual directory).
103
9.38k
  if (NamedDirEnt.second)
104
2.89k
    return;
105
6.48k
106
6.48k
  // Add the virtual directory to the cache.
107
6.48k
  auto UDE = std::make_unique<DirectoryEntry>();
108
6.48k
  UDE->Name = NamedDirEnt.first();
109
6.48k
  NamedDirEnt.second = *UDE.get();
110
6.48k
  VirtualDirectoryEntries.push_back(std::move(UDE));
111
6.48k
112
6.48k
  // Recursively add the other ancestors.
113
6.48k
  addAncestorsAsVirtualDirs(DirName);
114
6.48k
}
115
116
llvm::Expected<DirectoryEntryRef>
117
20.9M
FileManager::getDirectoryRef(StringRef DirName, bool CacheFailure) {
118
20.9M
  // stat doesn't like trailing separators except for root directory.
119
20.9M
  // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
120
20.9M
  // (though it can strip '\\')
121
20.9M
  if (DirName.size() > 1 &&
122
20.9M
      
DirName != llvm::sys::path::root_path(DirName)19.9M
&&
123
20.9M
      
llvm::sys::path::is_separator(DirName.back())19.9M
)
124
26.2k
    DirName = DirName.substr(0, DirName.size()-1);
125
#ifdef _WIN32
126
  // Fixing a problem with "clang C:test.c" on Windows.
127
  // Stat("C:") does not recognize "C:" as a valid directory
128
  std::string DirNameStr;
129
  if (DirName.size() > 1 && DirName.back() == ':' &&
130
      DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
131
    DirNameStr = DirName.str() + '.';
132
    DirName = DirNameStr;
133
  }
134
#endif
135
136
20.9M
  ++NumDirLookups;
137
20.9M
138
20.9M
  // See if there was already an entry in the map.  Note that the map
139
20.9M
  // contains both virtual and real directories.
140
20.9M
  auto SeenDirInsertResult =
141
20.9M
      SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory});
142
20.9M
  if (!SeenDirInsertResult.second) {
143
19.7M
    if (SeenDirInsertResult.first->second)
144
16.9M
      return DirectoryEntryRef(&*SeenDirInsertResult.first);
145
2.75M
    return llvm::errorCodeToError(SeenDirInsertResult.first->second.getError());
146
2.75M
  }
147
1.22M
148
1.22M
  // We've not seen this before. Fill it in.
149
1.22M
  ++NumDirCacheMisses;
150
1.22M
  auto &NamedDirEnt = *SeenDirInsertResult.first;
151
1.22M
  assert(!NamedDirEnt.second && "should be newly-created");
152
1.22M
153
1.22M
  // Get the null-terminated directory name as stored as the key of the
154
1.22M
  // SeenDirEntries map.
155
1.22M
  StringRef InterndDirName = NamedDirEnt.first();
156
1.22M
157
1.22M
  // Check to see if the directory exists.
158
1.22M
  llvm::vfs::Status Status;
159
1.22M
  auto statError = getStatValue(InterndDirName, Status, false,
160
1.22M
                                nullptr /*directory lookup*/);
161
1.22M
  if (statError) {
162
781k
    // There's no real directory at the given path.
163
781k
    if (CacheFailure)
164
780k
      NamedDirEnt.second = statError;
165
626
    else
166
626
      SeenDirEntries.erase(DirName);
167
781k
    return llvm::errorCodeToError(statError);
168
781k
  }
169
439k
170
439k
  // It exists.  See if we have already opened a directory with the
171
439k
  // same inode (this occurs on Unix-like systems when one dir is
172
439k
  // symlinked to another, for example) or the same path (on
173
439k
  // Windows).
174
439k
  DirectoryEntry &UDE = UniqueRealDirs[Status.getUniqueID()];
175
439k
176
439k
  NamedDirEnt.second = UDE;
177
439k
  if (UDE.getName().empty()) {
178
433k
    // We don't have this directory yet, add it.  We use the string
179
433k
    // key from the SeenDirEntries map as the string.
180
433k
    UDE.Name  = InterndDirName;
181
433k
  }
182
439k
183
439k
  return DirectoryEntryRef(&NamedDirEnt);
184
439k
}
185
186
llvm::ErrorOr<const DirectoryEntry *>
187
20.7M
FileManager::getDirectory(StringRef DirName, bool CacheFailure) {
188
20.7M
  auto Result = getDirectoryRef(DirName, CacheFailure);
189
20.7M
  if (Result)
190
17.2M
    return &Result->getDirEntry();
191
3.47M
  return llvm::errorToErrorCode(Result.takeError());
192
3.47M
}
193
194
llvm::ErrorOr<const FileEntry *>
195
3.36M
FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) {
196
3.36M
  auto Result = getFileRef(Filename, openFile, CacheFailure);
197
3.36M
  if (Result)
198
3.07M
    return &Result->getFileEntry();
199
287k
  return llvm::errorToErrorCode(Result.takeError());
200
287k
}
201
202
llvm::Expected<FileEntryRef>
203
8.88M
FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) {
204
8.88M
  ++NumFileLookups;
205
8.88M
206
8.88M
  // See if there is already an entry in the map.
207
8.88M
  auto SeenFileInsertResult =
208
8.88M
      SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
209
8.88M
  if (!SeenFileInsertResult.second) {
210
3.08M
    if (!SeenFileInsertResult.first->second)
211
99.9k
      return llvm::errorCodeToError(
212
99.9k
          SeenFileInsertResult.first->second.getError());
213
2.98M
    // Construct and return and FileEntryRef, unless it's a redirect to another
214
2.98M
    // filename.
215
2.98M
    SeenFileEntryOrRedirect Value = *SeenFileInsertResult.first->second;
216
2.98M
    FileEntry *FE;
217
2.98M
    if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>()))
218
2.98M
      
return FileEntryRef(SeenFileInsertResult.first->first(), *FE)2.98M
;
219
469
    return getFileRef(*Value.get<const StringRef *>(), openFile, CacheFailure);
220
469
  }
221
5.79M
222
5.79M
  // We've not seen this before. Fill it in.
223
5.79M
  ++NumFileCacheMisses;
224
5.79M
  auto *NamedFileEnt = &*SeenFileInsertResult.first;
225
5.79M
  assert(!NamedFileEnt->second && "should be newly-created");
226
5.79M
227
5.79M
  // Get the null-terminated file name as stored as the key of the
228
5.79M
  // SeenFileEntries map.
229
5.79M
  StringRef InterndFileName = NamedFileEnt->first();
230
5.79M
231
5.79M
  // Look up the directory for the file.  When looking up something like
232
5.79M
  // sys/foo.h we'll discover all of the search directories that have a 'sys'
233
5.79M
  // subdirectory.  This will let us avoid having to waste time on known-to-fail
234
5.79M
  // searches when we go to find sys/bar.h, because all the search directories
235
5.79M
  // without a 'sys' subdir will get a cached failure result.
236
5.79M
  auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
237
5.79M
  if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
238
2.97M
    if (CacheFailure)
239
2.97M
      NamedFileEnt->second = DirInfoOrErr.getError();
240
627
    else
241
627
      SeenFileEntries.erase(Filename);
242
2.97M
243
2.97M
    return llvm::errorCodeToError(DirInfoOrErr.getError());
244
2.97M
  }
245
2.82M
  const DirectoryEntry *DirInfo = *DirInfoOrErr;
246
2.82M
247
2.82M
  // FIXME: Use the directory info to prune this, before doing the stat syscall.
248
2.82M
  // FIXME: This will reduce the # syscalls.
249
2.82M
250
2.82M
  // Check to see if the file exists.
251
2.82M
  std::unique_ptr<llvm::vfs::File> F;
252
2.82M
  llvm::vfs::Status Status;
253
2.82M
  auto statError = getStatValue(InterndFileName, Status, true,
254
2.82M
                                openFile ? 
&F961k
:
nullptr1.86M
);
255
2.82M
  if (statError) {
256
497k
    // There's no real file at the given path.
257
497k
    if (CacheFailure)
258
496k
      NamedFileEnt->second = statError;
259
899
    else
260
899
      SeenFileEntries.erase(Filename);
261
497k
262
497k
    return llvm::errorCodeToError(statError);
263
497k
  }
264
2.32M
265
2.32M
  assert((openFile || !F) && "undesired open file");
266
2.32M
267
2.32M
  // It exists.  See if we have already opened a file with the same inode.
268
2.32M
  // This occurs when one dir is symlinked to another, for example.
269
2.32M
  FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()];
270
2.32M
271
2.32M
  NamedFileEnt->second = &UFE;
272
2.32M
273
2.32M
  // If the name returned by getStatValue is different than Filename, re-intern
274
2.32M
  // the name.
275
2.32M
  if (Status.getName() != Filename) {
276
174
    auto &NewNamedFileEnt =
277
174
        *SeenFileEntries.insert({Status.getName(), &UFE}).first;
278
174
    assert((*NewNamedFileEnt.second).get<FileEntry *>() == &UFE &&
279
174
           "filename from getStatValue() refers to wrong file");
280
174
    InterndFileName = NewNamedFileEnt.first().data();
281
174
    // In addition to re-interning the name, construct a redirecting seen file
282
174
    // entry, that will point to the name the filesystem actually wants to use.
283
174
    StringRef *Redirect = new (CanonicalNameStorage) StringRef(InterndFileName);
284
174
    auto SeenFileInsertResultIt = SeenFileEntries.find(Filename);
285
174
    assert(SeenFileInsertResultIt != SeenFileEntries.end() &&
286
174
           "unexpected SeenFileEntries cache miss");
287
174
    SeenFileInsertResultIt->second = Redirect;
288
174
    NamedFileEnt = &*SeenFileInsertResultIt;
289
174
  }
290
2.32M
291
2.32M
  if (UFE.isValid()) { // Already have an entry with this inode, return it.
292
8.53k
293
8.53k
    // FIXME: this hack ensures that if we look up a file by a virtual path in
294
8.53k
    // the VFS that the getDir() will have the virtual path, even if we found
295
8.53k
    // the file by a 'real' path first. This is required in order to find a
296
8.53k
    // module's structure when its headers/module map are mapped in the VFS.
297
8.53k
    // We should remove this as soon as we can properly support a file having
298
8.53k
    // multiple names.
299
8.53k
    if (DirInfo != UFE.Dir && 
Status.IsVFSMapped4.94k
)
300
12
      UFE.Dir = DirInfo;
301
8.53k
302
8.53k
    // Always update the name to use the last name by which a file was accessed.
303
8.53k
    // FIXME: Neither this nor always using the first name is correct; we want
304
8.53k
    // to switch towards a design where we return a FileName object that
305
8.53k
    // encapsulates both the name by which the file was accessed and the
306
8.53k
    // corresponding FileEntry.
307
8.53k
    // FIXME: The Name should be removed from FileEntry once all clients
308
8.53k
    // adopt FileEntryRef.
309
8.53k
    UFE.Name = InterndFileName;
310
8.53k
311
8.53k
    return FileEntryRef(InterndFileName, UFE);
312
8.53k
  }
313
2.31M
314
2.31M
  // Otherwise, we don't have this file yet, add it.
315
2.31M
  UFE.Name    = InterndFileName;
316
2.31M
  UFE.Size    = Status.getSize();
317
2.31M
  UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
318
2.31M
  UFE.Dir     = DirInfo;
319
2.31M
  UFE.UID     = NextFileUID++;
320
2.31M
  UFE.UniqueID = Status.getUniqueID();
321
2.31M
  UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
322
2.31M
  UFE.File = std::move(F);
323
2.31M
  UFE.IsValid = true;
324
2.31M
325
2.31M
  if (UFE.File) {
326
563k
    if (auto PathName = UFE.File->getName())
327
563k
      fillRealPathName(&UFE, *PathName);
328
1.75M
  } else 
if (1.75M
!openFile1.75M
) {
329
1.75M
    // We should still fill the path even if we aren't opening the file.
330
1.75M
    fillRealPathName(&UFE, InterndFileName);
331
1.75M
  }
332
2.31M
  return FileEntryRef(InterndFileName, UFE);
333
2.31M
}
334
335
const FileEntry *
336
FileManager::getVirtualFile(StringRef Filename, off_t Size,
337
3.07k
                            time_t ModificationTime) {
338
3.07k
  ++NumFileLookups;
339
3.07k
340
3.07k
  // See if there is already an entry in the map for an existing file.
341
3.07k
  auto &NamedFileEnt = *SeenFileEntries.insert(
342
3.07k
      {Filename, std::errc::no_such_file_or_directory}).first;
343
3.07k
  if (NamedFileEnt.second) {
344
180
    SeenFileEntryOrRedirect Value = *NamedFileEnt.second;
345
180
    FileEntry *FE;
346
180
    if (LLVM_LIKELY(FE = Value.dyn_cast<FileEntry *>()))
347
180
      return FE;
348
0
    return getVirtualFile(*Value.get<const StringRef *>(), Size,
349
0
                          ModificationTime);
350
0
  }
351
2.89k
352
2.89k
  // We've not seen this before, or the file is cached as non-existent.
353
2.89k
  ++NumFileCacheMisses;
354
2.89k
  addAncestorsAsVirtualDirs(Filename);
355
2.89k
  FileEntry *UFE = nullptr;
356
2.89k
357
2.89k
  // Now that all ancestors of Filename are in the cache, the
358
2.89k
  // following call is guaranteed to find the DirectoryEntry from the
359
2.89k
  // cache.
360
2.89k
  auto DirInfo = getDirectoryFromFile(*this, Filename, /*CacheFailure=*/true);
361
2.89k
  assert(DirInfo &&
362
2.89k
         "The directory of a virtual file should already be in the cache.");
363
2.89k
364
2.89k
  // Check to see if the file exists. If so, drop the virtual file
365
2.89k
  llvm::vfs::Status Status;
366
2.89k
  const char *InterndFileName = NamedFileEnt.first().data();
367
2.89k
  if (!getStatValue(InterndFileName, Status, true, nullptr)) {
368
463
    UFE = &UniqueRealFiles[Status.getUniqueID()];
369
463
    Status = llvm::vfs::Status(
370
463
      Status.getName(), Status.getUniqueID(),
371
463
      llvm::sys::toTimePoint(ModificationTime),
372
463
      Status.getUser(), Status.getGroup(), Size,
373
463
      Status.getType(), Status.getPermissions());
374
463
375
463
    NamedFileEnt.second = UFE;
376
463
377
463
    // If we had already opened this file, close it now so we don't
378
463
    // leak the descriptor. We're not going to use the file
379
463
    // descriptor anyway, since this is a virtual file.
380
463
    if (UFE->File)
381
0
      UFE->closeFile();
382
463
383
463
    // If we already have an entry with this inode, return it.
384
463
    if (UFE->isValid())
385
1
      return UFE;
386
462
387
462
    UFE->UniqueID = Status.getUniqueID();
388
462
    UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
389
462
    fillRealPathName(UFE, Status.getName());
390
2.43k
  } else {
391
2.43k
    VirtualFileEntries.push_back(std::make_unique<FileEntry>());
392
2.43k
    UFE = VirtualFileEntries.back().get();
393
2.43k
    NamedFileEnt.second = UFE;
394
2.43k
  }
395
2.89k
396
2.89k
  UFE->Name    = InterndFileName;
397
2.89k
  UFE->Size    = Size;
398
2.89k
  UFE->ModTime = ModificationTime;
399
2.89k
  UFE->Dir     = *DirInfo;
400
2.89k
  UFE->UID     = NextFileUID++;
401
2.89k
  UFE->IsValid = true;
402
2.89k
  UFE->File.reset();
403
2.89k
  return UFE;
404
2.89k
}
405
406
2
llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) {
407
2
  // Stat of the file and return nullptr if it doesn't exist.
408
2
  llvm::vfs::Status Status;
409
2
  if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr))
410
0
    return None;
411
2
412
2
  // Fill it in from the stat.
413
2
  BypassFileEntries.push_back(std::make_unique<FileEntry>());
414
2
  const FileEntry &VFE = VF.getFileEntry();
415
2
  FileEntry &BFE = *BypassFileEntries.back();
416
2
  BFE.Name = VFE.getName();
417
2
  BFE.Size = Status.getSize();
418
2
  BFE.Dir = VFE.Dir;
419
2
  BFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
420
2
  BFE.UID = NextFileUID++;
421
2
  BFE.IsValid = true;
422
2
  return FileEntryRef(VF.getName(), BFE);
423
2
}
424
425
2.43M
bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
426
2.43M
  StringRef pathRef(path.data(), path.size());
427
2.43M
428
2.43M
  if (FileSystemOpts.WorkingDir.empty()
429
2.43M
      || 
llvm::sys::path::is_absolute(pathRef)1.37k
)
430
2.43M
    return false;
431
312
432
312
  SmallString<128> NewPath(FileSystemOpts.WorkingDir);
433
312
  llvm::sys::path::append(NewPath, pathRef);
434
312
  path = NewPath;
435
312
  return true;
436
312
}
437
438
2.41M
bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
439
2.41M
  bool Changed = FixupRelativePath(Path);
440
2.41M
441
2.41M
  if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
442
68.1k
    FS->makeAbsolute(Path);
443
68.1k
    Changed = true;
444
68.1k
  }
445
2.41M
446
2.41M
  return Changed;
447
2.41M
}
448
449
2.31M
void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
450
2.31M
  llvm::SmallString<128> AbsPath(FileName);
451
2.31M
  // This is not the same as `VFS::getRealPath()`, which resolves symlinks
452
2.31M
  // but can be very expensive on real file systems.
453
2.31M
  // FIXME: the semantic of RealPathName is unclear, and the name might be
454
2.31M
  // misleading. We need to clean up the interface here.
455
2.31M
  makeAbsolutePath(AbsPath);
456
2.31M
  llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
457
2.31M
  UFE->RealPathName = std::string(AbsPath.str());
458
2.31M
}
459
460
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
461
916k
FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile) {
462
916k
  uint64_t FileSize = Entry->getSize();
463
916k
  // If there's a high enough chance that the file have changed since we
464
916k
  // got its size, force a stat before opening it.
465
916k
  if (isVolatile)
466
20.2k
    FileSize = -1;
467
916k
468
916k
  StringRef Filename = Entry->getName();
469
916k
  // If the file is already open, use the open file descriptor.
470
916k
  if (Entry->File) {
471
560k
    auto Result =
472
560k
        Entry->File->getBuffer(Filename, FileSize,
473
560k
                               /*RequiresNullTerminator=*/true, isVolatile);
474
560k
    Entry->closeFile();
475
560k
    return Result;
476
560k
  }
477
356k
478
356k
  // Otherwise, open the file.
479
356k
  return getBufferForFileImpl(Filename, FileSize, isVolatile);
480
356k
}
481
482
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
483
FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
484
359k
                                  bool isVolatile) {
485
359k
  if (FileSystemOpts.WorkingDir.empty())
486
359k
    return FS->getBufferForFile(Filename, FileSize,
487
359k
                                /*RequiresNullTerminator=*/true, isVolatile);
488
119
489
119
  SmallString<128> FilePath(Filename);
490
119
  FixupRelativePath(FilePath);
491
119
  return FS->getBufferForFile(FilePath, FileSize,
492
119
                              /*RequiresNullTerminator=*/true, isVolatile);
493
119
}
494
495
/// getStatValue - Get the 'stat' information for the specified path,
496
/// using the cache to accelerate it if possible.  This returns true
497
/// if the path points to a virtual file or does not exist, or returns
498
/// false if it's an existent real file.  If FileDescriptor is NULL,
499
/// do directory look-up instead of file look-up.
500
std::error_code
501
FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
502
4.04M
                          bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
503
4.04M
  // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
504
4.04M
  // absolute!
505
4.04M
  if (FileSystemOpts.WorkingDir.empty())
506
4.04M
    return FileSystemStatCache::get(Path, Status, isFile, F,
507
4.04M
                                    StatCache.get(), *FS);
508
848
509
848
  SmallString<128> FilePath(Path);
510
848
  FixupRelativePath(FilePath);
511
848
512
848
  return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
513
848
                                  StatCache.get(), *FS);
514
848
}
515
516
std::error_code
517
FileManager::getNoncachedStatValue(StringRef Path,
518
16.1k
                                   llvm::vfs::Status &Result) {
519
16.1k
  SmallString<128> FilePath(Path);
520
16.1k
  FixupRelativePath(FilePath);
521
16.1k
522
16.1k
  llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
523
16.1k
  if (!S)
524
16.1k
    return S.getError();
525
9
  Result = *S;
526
9
  return std::error_code();
527
9
}
528
529
void FileManager::GetUniqueIDMapping(
530
4.35k
                   SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
531
4.35k
  UIDToFiles.clear();
532
4.35k
  UIDToFiles.resize(NextFileUID);
533
4.35k
534
4.35k
  // Map file entries
535
4.35k
  for (llvm::StringMap<llvm::ErrorOr<SeenFileEntryOrRedirect>,
536
4.35k
                       llvm::BumpPtrAllocator>::const_iterator
537
4.35k
           FE = SeenFileEntries.begin(),
538
4.35k
           FEEnd = SeenFileEntries.end();
539
898k
       FE != FEEnd; 
++FE894k
)
540
894k
    if (llvm::ErrorOr<SeenFileEntryOrRedirect> Entry = FE->getValue()) {
541
357k
      if (const auto *FE = (*Entry).dyn_cast<FileEntry *>())
542
357k
        UIDToFiles[FE->getUID()] = FE;
543
357k
    }
544
4.35k
545
4.35k
  // Map virtual file entries
546
4.35k
  for (const auto &VFE : VirtualFileEntries)
547
458
    UIDToFiles[VFE->getUID()] = VFE.get();
548
4.35k
}
549
550
895k
StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
551
895k
  llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
552
895k
    = CanonicalNames.find(Dir);
553
895k
  if (Known != CanonicalNames.end())
554
870k
    return Known->second;
555
25.0k
556
25.0k
  StringRef CanonicalName(Dir->getName());
557
25.0k
558
25.0k
  SmallString<4096> CanonicalNameBuf;
559
25.0k
  if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
560
24.9k
    CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
561
25.0k
562
25.0k
  CanonicalNames.insert({Dir, CanonicalName});
563
25.0k
  return CanonicalName;
564
25.0k
}
565
566
3
StringRef FileManager::getCanonicalName(const FileEntry *File) {
567
3
  llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
568
3
    = CanonicalNames.find(File);
569
3
  if (Known != CanonicalNames.end())
570
1
    return Known->second;
571
2
572
2
  StringRef CanonicalName(File->getName());
573
2
574
2
  SmallString<4096> CanonicalNameBuf;
575
2
  if (!FS->getRealPath(File->getName(), CanonicalNameBuf))
576
2
    CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
577
2
578
2
  CanonicalNames.insert({File, CanonicalName});
579
2
  return CanonicalName;
580
2
}
581
582
4
void FileManager::PrintStats() const {
583
4
  llvm::errs() << "\n*** File Manager Stats:\n";
584
4
  llvm::errs() << UniqueRealFiles.size() << " real files found, "
585
4
               << UniqueRealDirs.size() << " real dirs found.\n";
586
4
  llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
587
4
               << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
588
4
  llvm::errs() << NumDirLookups << " dir lookups, "
589
4
               << NumDirCacheMisses << " dir cache misses.\n";
590
4
  llvm::errs() << NumFileLookups << " file lookups, "
591
4
               << NumFileCacheMisses << " file cache misses.\n";
592
4
593
4
  //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
594
4
}