Coverage Report

Created: 2021-01-26 06:56

/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
180k
      SeenFileEntries(64), NextFileUID(0) {
55
  // If the caller doesn't provide a virtual file system, just grab the real
56
  // file system.
57
180k
  if (!this->FS)
58
290
    this->FS = llvm::vfs::getRealFileSystem();
59
180k
}
60
61
174k
FileManager::~FileManager() = default;
62
63
14
void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
64
14
  assert(statCache && "No stat cache provided?");
65
14
  StatCache = std::move(statCache);
66
14
}
67
68
16.6k
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::Expected<DirectoryEntryRef>
73
getDirectoryFromFile(FileManager &FileMgr, StringRef Filename,
74
3.57M
                     bool CacheFailure) {
75
3.57M
  if (Filename.empty())
76
0
    return llvm::errorCodeToError(
77
0
        make_error_code(std::errc::no_such_file_or_directory));
78
79
3.57M
  if (llvm::sys::path::is_separator(Filename[Filename.size() - 1]))
80
20
    return llvm::errorCodeToError(make_error_code(std::errc::is_a_directory));
81
82
3.57M
  StringRef DirName = llvm::sys::path::parent_path(Filename);
83
  // Use the current directory if file has no path component.
84
3.57M
  if (DirName.empty())
85
79.6k
    DirName = ".";
86
87
3.57M
  return FileMgr.getDirectoryRef(DirName, CacheFailure);
88
3.57M
}
89
90
/// Add all ancestors of the given path (pointing to either a file or
91
/// a directory) as virtual directories.
92
14.0k
void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
93
14.0k
  StringRef DirName = llvm::sys::path::parent_path(Path);
94
14.0k
  if (DirName.empty())
95
7.11k
    DirName = ".";
96
97
14.0k
  auto &NamedDirEnt = *SeenDirEntries.insert(
98
14.0k
        {DirName, std::errc::no_such_file_or_directory}).first;
99
100
  // When caching a virtual directory, we always cache its ancestors
101
  // at the same time.  Therefore, if DirName is already in the cache,
102
  // we don't need to recurse as its ancestors must also already be in
103
  // the cache (or it's a known non-virtual directory).
104
14.0k
  if (NamedDirEnt.second)
105
5.12k
    return;
106
107
  // Add the virtual directory to the cache.
108
8.89k
  auto UDE = std::make_unique<DirectoryEntry>();
109
8.89k
  UDE->Name = NamedDirEnt.first();
110
8.89k
  NamedDirEnt.second = *UDE.get();
111
8.89k
  VirtualDirectoryEntries.push_back(std::move(UDE));
112
113
  // Recursively add the other ancestors.
114
8.89k
  addAncestorsAsVirtualDirs(DirName);
115
8.89k
}
116
117
llvm::Expected<DirectoryEntryRef>
118
11.9M
FileManager::getDirectoryRef(StringRef DirName, bool CacheFailure) {
119
  // stat doesn't like trailing separators except for root directory.
120
  // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
121
  // (though it can strip '\\')
122
11.9M
  if (DirName.size() > 1 &&
123
11.4M
      DirName != llvm::sys::path::root_path(DirName) &&
124
11.4M
      llvm::sys::path::is_separator(DirName.back()))
125
15.7k
    DirName = DirName.substr(0, DirName.size()-1);
126
#ifdef _WIN32
127
  // Fixing a problem with "clang C:test.c" on Windows.
128
  // Stat("C:") does not recognize "C:" as a valid directory
129
  std::string DirNameStr;
130
  if (DirName.size() > 1 && DirName.back() == ':' &&
131
      DirName.equals_lower(llvm::sys::path::root_name(DirName))) {
132
    DirNameStr = DirName.str() + '.';
133
    DirName = DirNameStr;
134
  }
135
#endif
136
137
11.9M
  ++NumDirLookups;
138
139
  // See if there was already an entry in the map.  Note that the map
140
  // contains both virtual and real directories.
141
11.9M
  auto SeenDirInsertResult =
142
11.9M
      SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory});
143
11.9M
  if (!SeenDirInsertResult.second) {
144
10.9M
    if (SeenDirInsertResult.first->second)
145
9.45M
      return DirectoryEntryRef(*SeenDirInsertResult.first);
146
1.47M
    return llvm::errorCodeToError(SeenDirInsertResult.first->second.getError());
147
1.47M
  }
148
149
  // We've not seen this before. Fill it in.
150
1.04M
  ++NumDirCacheMisses;
151
1.04M
  auto &NamedDirEnt = *SeenDirInsertResult.first;
152
1.04M
  assert(!NamedDirEnt.second && "should be newly-created");
153
154
  // Get the null-terminated directory name as stored as the key of the
155
  // SeenDirEntries map.
156
1.04M
  StringRef InterndDirName = NamedDirEnt.first();
157
158
  // Check to see if the directory exists.
159
1.04M
  llvm::vfs::Status Status;
160
1.04M
  auto statError = getStatValue(InterndDirName, Status, false,
161
1.04M
                                nullptr /*directory lookup*/);
162
1.04M
  if (statError) {
163
    // There's no real directory at the given path.
164
638k
    if (CacheFailure)
165
637k
      NamedDirEnt.second = statError;
166
638
    else
167
638
      SeenDirEntries.erase(DirName);
168
638k
    return llvm::errorCodeToError(statError);
169
638k
  }
170
171
  // It exists.  See if we have already opened a directory with the
172
  // same inode (this occurs on Unix-like systems when one dir is
173
  // symlinked to another, for example) or the same path (on
174
  // Windows).
175
408k
  DirectoryEntry &UDE = UniqueRealDirs[Status.getUniqueID()];
176
177
408k
  NamedDirEnt.second = UDE;
178
408k
  if (UDE.getName().empty()) {
179
    // We don't have this directory yet, add it.  We use the string
180
    // key from the SeenDirEntries map as the string.
181
405k
    UDE.Name  = InterndDirName;
182
405k
  }
183
184
408k
  return DirectoryEntryRef(NamedDirEnt);
185
408k
}
186
187
llvm::ErrorOr<const DirectoryEntry *>
188
8.15M
FileManager::getDirectory(StringRef DirName, bool CacheFailure) {
189
8.15M
  auto Result = getDirectoryRef(DirName, CacheFailure);
190
8.15M
  if (Result)
191
7.66M
    return &Result->getDirEntry();
192
489k
  return llvm::errorToErrorCode(Result.takeError());
193
489k
}
194
195
llvm::ErrorOr<const FileEntry *>
196
571k
FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) {
197
571k
  auto Result = getFileRef(Filename, openFile, CacheFailure);
198
571k
  if (Result)
199
413k
    return &Result->getFileEntry();
200
158k
  return llvm::errorToErrorCode(Result.takeError());
201
158k
}
202
203
llvm::Expected<FileEntryRef>
204
5.75M
FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) {
205
5.75M
  ++NumFileLookups;
206
207
  // See if there is already an entry in the map.
208
5.75M
  auto SeenFileInsertResult =
209
5.75M
      SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
210
5.75M
  if (!SeenFileInsertResult.second) {
211
2.18M
    if (!SeenFileInsertResult.first->second)
212
66.1k
      return llvm::errorCodeToError(
213
66.1k
          SeenFileInsertResult.first->second.getError());
214
    // Construct and return and FileEntryRef, unless it's a redirect to another
215
    // filename.
216
2.12M
    FileEntryRef::MapValue Value = *SeenFileInsertResult.first->second;
217
2.12M
    if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
218
2.12M
      return FileEntryRef(*SeenFileInsertResult.first);
219
485
    return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
220
485
        Value.V.get<const void *>()));
221
485
  }
222
223
  // We've not seen this before. Fill it in.
224
3.56M
  ++NumFileCacheMisses;
225
3.56M
  auto *NamedFileEnt = &*SeenFileInsertResult.first;
226
3.56M
  assert(!NamedFileEnt->second && "should be newly-created");
227
228
  // Get the null-terminated file name as stored as the key of the
229
  // SeenFileEntries map.
230
3.56M
  StringRef InterndFileName = NamedFileEnt->first();
231
232
  // Look up the directory for the file.  When looking up something like
233
  // sys/foo.h we'll discover all of the search directories that have a 'sys'
234
  // subdirectory.  This will let us avoid having to waste time on known-to-fail
235
  // searches when we go to find sys/bar.h, because all the search directories
236
  // without a 'sys' subdir will get a cached failure result.
237
3.56M
  auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
238
3.56M
  if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
239
1.55M
    std::error_code Err = errorToErrorCode(DirInfoOrErr.takeError());
240
1.55M
    if (CacheFailure)
241
1.55M
      NamedFileEnt->second = Err;
242
639
    else
243
639
      SeenFileEntries.erase(Filename);
244
245
1.55M
    return llvm::errorCodeToError(Err);
246
1.55M
  }
247
2.01M
  DirectoryEntryRef DirInfo = *DirInfoOrErr;
248
249
  // FIXME: Use the directory info to prune this, before doing the stat syscall.
250
  // FIXME: This will reduce the # syscalls.
251
252
  // Check to see if the file exists.
253
2.01M
  std::unique_ptr<llvm::vfs::File> F;
254
2.01M
  llvm::vfs::Status Status;
255
2.01M
  auto statError = getStatValue(InterndFileName, Status, true,
256
1.42M
                                openFile ? 
&F590k
: nullptr);
257
2.01M
  if (statError) {
258
    // There's no real file at the given path.
259
308k
    if (CacheFailure)
260
307k
      NamedFileEnt->second = statError;
261
909
    else
262
909
      SeenFileEntries.erase(Filename);
263
264
308k
    return llvm::errorCodeToError(statError);
265
308k
  }
266
267
1.70M
  assert((openFile || !F) && "undesired open file");
268
269
  // It exists.  See if we have already opened a file with the same inode.
270
  // This occurs when one dir is symlinked to another, for example.
271
1.70M
  FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()];
272
273
1.70M
  if (Status.getName() == Filename) {
274
    // The name matches. Set the FileEntry.
275
1.70M
    NamedFileEnt->second = FileEntryRef::MapValue(UFE, DirInfo);
276
191
  } else {
277
    // Name mismatch. We need a redirect. First grab the actual entry we want
278
    // to return.
279
191
    auto &Redirection =
280
191
        *SeenFileEntries
281
191
             .insert({Status.getName(), FileEntryRef::MapValue(UFE, DirInfo)})
282
191
             .first;
283
191
    assert(Redirection.second->V.is<FileEntry *>() &&
284
191
           "filename redirected to a non-canonical filename?");
285
191
    assert(Redirection.second->V.get<FileEntry *>() == &UFE &&
286
191
           "filename from getStatValue() refers to wrong file");
287
288
    // Cache the redirection in the previously-inserted entry, still available
289
    // in the tentative return value.
290
191
    NamedFileEnt->second = FileEntryRef::MapValue(Redirection);
291
292
    // Fix the tentative return value.
293
191
    NamedFileEnt = &Redirection;
294
191
  }
295
296
1.70M
  FileEntryRef ReturnedRef(*NamedFileEnt);
297
1.70M
  if (UFE.isValid()) { // Already have an entry with this inode, return it.
298
299
    // FIXME: this hack ensures that if we look up a file by a virtual path in
300
    // the VFS that the getDir() will have the virtual path, even if we found
301
    // the file by a 'real' path first. This is required in order to find a
302
    // module's structure when its headers/module map are mapped in the VFS.
303
    // We should remove this as soon as we can properly support a file having
304
    // multiple names.
305
5.72k
    if (&DirInfo.getDirEntry() != UFE.Dir && 
Status.IsVFSMapped2.95k
)
306
12
      UFE.Dir = &DirInfo.getDirEntry();
307
308
    // Always update LastRef to the last name by which a file was accessed.
309
    // FIXME: Neither this nor always using the first reference is correct; we
310
    // want to switch towards a design where we return a FileName object that
311
    // encapsulates both the name by which the file was accessed and the
312
    // corresponding FileEntry.
313
    // FIXME: LastRef should be removed from FileEntry once all clients adopt
314
    // FileEntryRef.
315
5.72k
    UFE.LastRef = ReturnedRef;
316
317
5.72k
    return ReturnedRef;
318
5.72k
  }
319
320
  // Otherwise, we don't have this file yet, add it.
321
1.70M
  UFE.LastRef = ReturnedRef;
322
1.70M
  UFE.Size    = Status.getSize();
323
1.70M
  UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
324
1.70M
  UFE.Dir     = &DirInfo.getDirEntry();
325
1.70M
  UFE.UID     = NextFileUID++;
326
1.70M
  UFE.UniqueID = Status.getUniqueID();
327
1.70M
  UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
328
1.70M
  UFE.File = std::move(F);
329
1.70M
  UFE.IsValid = true;
330
331
1.70M
  if (UFE.File) {
332
367k
    if (auto PathName = UFE.File->getName())
333
367k
      fillRealPathName(&UFE, *PathName);
334
1.33M
  } else 
if (1.33M
!openFile1.33M
) {
335
    // We should still fill the path even if we aren't opening the file.
336
1.33M
    fillRealPathName(&UFE, InterndFileName);
337
1.33M
  }
338
1.70M
  return ReturnedRef;
339
1.70M
}
340
341
648
llvm::Expected<FileEntryRef> FileManager::getSTDIN() {
342
  // Only read stdin once.
343
648
  if (STDIN)
344
0
    return *STDIN;
345
346
648
  std::unique_ptr<llvm::MemoryBuffer> Content;
347
648
  if (auto ContentOrError = llvm::MemoryBuffer::getSTDIN())
348
648
    Content = std::move(*ContentOrError);
349
0
  else
350
0
    return llvm::errorCodeToError(ContentOrError.getError());
351
352
648
  STDIN = getVirtualFileRef(Content->getBufferIdentifier(),
353
648
                            Content->getBufferSize(), 0);
354
648
  FileEntry &FE = const_cast<FileEntry &>(STDIN->getFileEntry());
355
648
  FE.Content = std::move(Content);
356
648
  FE.IsNamedPipe = true;
357
648
  return *STDIN;
358
648
}
359
360
const FileEntry *FileManager::getVirtualFile(StringRef Filename, off_t Size,
361
4.36k
                                             time_t ModificationTime) {
362
4.36k
  return &getVirtualFileRef(Filename, Size, ModificationTime).getFileEntry();
363
4.36k
}
364
365
FileEntryRef FileManager::getVirtualFileRef(StringRef Filename, off_t Size,
366
5.29k
                                            time_t ModificationTime) {
367
5.29k
  ++NumFileLookups;
368
369
  // See if there is already an entry in the map for an existing file.
370
5.29k
  auto &NamedFileEnt = *SeenFileEntries.insert(
371
5.29k
      {Filename, std::errc::no_such_file_or_directory}).first;
372
5.29k
  if (NamedFileEnt.second) {
373
168
    FileEntryRef::MapValue Value = *NamedFileEnt.second;
374
168
    if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
375
168
      return FileEntryRef(NamedFileEnt);
376
0
    return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
377
0
        Value.V.get<const void *>()));
378
0
  }
379
380
  // We've not seen this before, or the file is cached as non-existent.
381
5.12k
  ++NumFileCacheMisses;
382
5.12k
  addAncestorsAsVirtualDirs(Filename);
383
5.12k
  FileEntry *UFE = nullptr;
384
385
  // Now that all ancestors of Filename are in the cache, the
386
  // following call is guaranteed to find the DirectoryEntry from the
387
  // cache.
388
5.12k
  auto DirInfo = expectedToOptional(
389
5.12k
      getDirectoryFromFile(*this, Filename, /*CacheFailure=*/true));
390
5.12k
  assert(DirInfo &&
391
5.12k
         "The directory of a virtual file should already be in the cache.");
392
393
  // Check to see if the file exists. If so, drop the virtual file
394
5.12k
  llvm::vfs::Status Status;
395
5.12k
  const char *InterndFileName = NamedFileEnt.first().data();
396
5.12k
  if (!getStatValue(InterndFileName, Status, true, nullptr)) {
397
2.61k
    UFE = &UniqueRealFiles[Status.getUniqueID()];
398
2.61k
    Status = llvm::vfs::Status(
399
2.61k
      Status.getName(), Status.getUniqueID(),
400
2.61k
      llvm::sys::toTimePoint(ModificationTime),
401
2.61k
      Status.getUser(), Status.getGroup(), Size,
402
2.61k
      Status.getType(), Status.getPermissions());
403
404
2.61k
    NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo);
405
406
    // If we had already opened this file, close it now so we don't
407
    // leak the descriptor. We're not going to use the file
408
    // descriptor anyway, since this is a virtual file.
409
2.61k
    if (UFE->File)
410
0
      UFE->closeFile();
411
412
    // If we already have an entry with this inode, return it.
413
    //
414
    // FIXME: Surely this should add a reference by the new name, and return
415
    // it instead...
416
2.61k
    if (UFE->isValid())
417
1
      return FileEntryRef(NamedFileEnt);
418
419
2.61k
    UFE->UniqueID = Status.getUniqueID();
420
2.61k
    UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
421
2.61k
    fillRealPathName(UFE, Status.getName());
422
2.50k
  } else {
423
2.50k
    VirtualFileEntries.push_back(std::make_unique<FileEntry>());
424
2.50k
    UFE = VirtualFileEntries.back().get();
425
2.50k
    NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo);
426
2.50k
  }
427
428
5.12k
  UFE->LastRef = FileEntryRef(NamedFileEnt);
429
5.12k
  UFE->Size    = Size;
430
5.12k
  UFE->ModTime = ModificationTime;
431
5.12k
  UFE->Dir     = &DirInfo->getDirEntry();
432
5.12k
  UFE->UID     = NextFileUID++;
433
5.12k
  UFE->IsValid = true;
434
5.12k
  UFE->File.reset();
435
5.12k
  return FileEntryRef(NamedFileEnt);
436
5.12k
}
437
438
2
llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) {
439
  // Stat of the file and return nullptr if it doesn't exist.
440
2
  llvm::vfs::Status Status;
441
2
  if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr))
442
0
    return None;
443
444
2
  if (!SeenBypassFileEntries)
445
2
    SeenBypassFileEntries = std::make_unique<
446
2
        llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>();
447
448
  // If we've already bypassed just use the existing one.
449
2
  auto Insertion = SeenBypassFileEntries->insert(
450
2
      {VF.getName(), std::errc::no_such_file_or_directory});
451
2
  if (!Insertion.second)
452
0
    return FileEntryRef(*Insertion.first);
453
454
  // Fill in the new entry from the stat.
455
2
  BypassFileEntries.push_back(std::make_unique<FileEntry>());
456
2
  const FileEntry &VFE = VF.getFileEntry();
457
2
  FileEntry &BFE = *BypassFileEntries.back();
458
2
  Insertion.first->second = FileEntryRef::MapValue(BFE, VF.getDir());
459
2
  BFE.LastRef = FileEntryRef(*Insertion.first);
460
2
  BFE.Size = Status.getSize();
461
2
  BFE.Dir = VFE.Dir;
462
2
  BFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
463
2
  BFE.UID = NextFileUID++;
464
2
  BFE.IsValid = true;
465
466
  // Save the entry in the bypass table and return.
467
2
  return FileEntryRef(*Insertion.first);
468
2
}
469
470
1.81M
bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
471
1.81M
  StringRef pathRef(path.data(), path.size());
472
473
1.81M
  if (FileSystemOpts.WorkingDir.empty()
474
1.33k
      || llvm::sys::path::is_absolute(pathRef))
475
1.81M
    return false;
476
477
284
  SmallString<128> NewPath(FileSystemOpts.WorkingDir);
478
284
  llvm::sys::path::append(NewPath, pathRef);
479
284
  path = NewPath;
480
284
  return true;
481
284
}
482
483
1.79M
bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
484
1.79M
  bool Changed = FixupRelativePath(Path);
485
486
1.79M
  if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
487
92.7k
    FS->makeAbsolute(Path);
488
92.7k
    Changed = true;
489
92.7k
  }
490
491
1.79M
  return Changed;
492
1.79M
}
493
494
1.70M
void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
495
1.70M
  llvm::SmallString<128> AbsPath(FileName);
496
  // This is not the same as `VFS::getRealPath()`, which resolves symlinks
497
  // but can be very expensive on real file systems.
498
  // FIXME: the semantic of RealPathName is unclear, and the name might be
499
  // misleading. We need to clean up the interface here.
500
1.70M
  makeAbsolutePath(AbsPath);
501
1.70M
  llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
502
1.70M
  UFE->RealPathName = std::string(AbsPath.str());
503
1.70M
}
504
505
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
506
FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
507
639k
                              bool RequiresNullTerminator) {
508
  // If the content is living on the file entry, return a reference to it.
509
639k
  if (Entry->Content)
510
648
    return llvm::MemoryBuffer::getMemBuffer(Entry->Content->getMemBufferRef());
511
512
639k
  uint64_t FileSize = Entry->getSize();
513
  // If there's a high enough chance that the file have changed since we
514
  // got its size, force a stat before opening it.
515
639k
  if (isVolatile || 
Entry->isNamedPipe()620k
)
516
18.2k
    FileSize = -1;
517
518
639k
  StringRef Filename = Entry->getName();
519
  // If the file is already open, use the open file descriptor.
520
639k
  if (Entry->File) {
521
365k
    auto Result = Entry->File->getBuffer(Filename, FileSize,
522
365k
                                         RequiresNullTerminator, isVolatile);
523
365k
    Entry->closeFile();
524
365k
    return Result;
525
365k
  }
526
527
  // Otherwise, open the file.
528
273k
  return getBufferForFileImpl(Filename, FileSize, isVolatile,
529
273k
                              RequiresNullTerminator);
530
273k
}
531
532
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
533
FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
534
                                  bool isVolatile,
535
277k
                                  bool RequiresNullTerminator) {
536
277k
  if (FileSystemOpts.WorkingDir.empty())
537
277k
    return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator,
538
277k
                                isVolatile);
539
540
120
  SmallString<128> FilePath(Filename);
541
120
  FixupRelativePath(FilePath);
542
120
  return FS->getBufferForFile(FilePath, FileSize, RequiresNullTerminator,
543
120
                              isVolatile);
544
120
}
545
546
/// getStatValue - Get the 'stat' information for the specified path,
547
/// using the cache to accelerate it if possible.  This returns true
548
/// if the path points to a virtual file or does not exist, or returns
549
/// false if it's an existent real file.  If FileDescriptor is NULL,
550
/// do directory look-up instead of file look-up.
551
std::error_code
552
FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
553
3.06M
                          bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
554
  // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
555
  // absolute!
556
3.06M
  if (FileSystemOpts.WorkingDir.empty())
557
3.06M
    return FileSystemStatCache::get(Path, Status, isFile, F,
558
3.06M
                                    StatCache.get(), *FS);
559
560
796
  SmallString<128> FilePath(Path);
561
796
  FixupRelativePath(FilePath);
562
563
796
  return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
564
796
                                  StatCache.get(), *FS);
565
796
}
566
567
std::error_code
568
FileManager::getNoncachedStatValue(StringRef Path,
569
13.3k
                                   llvm::vfs::Status &Result) {
570
13.3k
  SmallString<128> FilePath(Path);
571
13.3k
  FixupRelativePath(FilePath);
572
573
13.3k
  llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
574
13.3k
  if (!S)
575
13.3k
    return S.getError();
576
10
  Result = *S;
577
10
  return std::error_code();
578
10
}
579
580
void FileManager::GetUniqueIDMapping(
581
5.16k
                   SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
582
5.16k
  UIDToFiles.clear();
583
5.16k
  UIDToFiles.resize(NextFileUID);
584
585
  // Map file entries
586
5.16k
  for (llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>,
587
5.16k
                       llvm::BumpPtrAllocator>::const_iterator
588
5.16k
           FE = SeenFileEntries.begin(),
589
5.16k
           FEEnd = SeenFileEntries.end();
590
934k
       FE != FEEnd; 
++FE928k
)
591
928k
    if (llvm::ErrorOr<FileEntryRef::MapValue> Entry = FE->getValue()) {
592
347k
      if (const auto *FE = Entry->V.dyn_cast<FileEntry *>())
593
347k
        UIDToFiles[FE->getUID()] = FE;
594
347k
    }
595
596
  // Map virtual file entries
597
5.16k
  for (const auto &VFE : VirtualFileEntries)
598
447
    UIDToFiles[VFE->getUID()] = VFE.get();
599
5.16k
}
600
601
480k
StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
602
480k
  llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
603
480k
    = CanonicalNames.find(Dir);
604
480k
  if (Known != CanonicalNames.end())
605
465k
    return Known->second;
606
607
15.3k
  StringRef CanonicalName(Dir->getName());
608
609
15.3k
  SmallString<4096> CanonicalNameBuf;
610
15.3k
  if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
611
15.3k
    CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
612
613
15.3k
  CanonicalNames.insert({Dir, CanonicalName});
614
15.3k
  return CanonicalName;
615
15.3k
}
616
617
3
StringRef FileManager::getCanonicalName(const FileEntry *File) {
618
3
  llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
619
3
    = CanonicalNames.find(File);
620
3
  if (Known != CanonicalNames.end())
621
1
    return Known->second;
622
623
2
  StringRef CanonicalName(File->getName());
624
625
2
  SmallString<4096> CanonicalNameBuf;
626
2
  if (!FS->getRealPath(File->getName(), CanonicalNameBuf))
627
2
    CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
628
629
2
  CanonicalNames.insert({File, CanonicalName});
630
2
  return CanonicalName;
631
2
}
632
633
4
void FileManager::PrintStats() const {
634
4
  llvm::errs() << "\n*** File Manager Stats:\n";
635
4
  llvm::errs() << UniqueRealFiles.size() << " real files found, "
636
4
               << UniqueRealDirs.size() << " real dirs found.\n";
637
4
  llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
638
4
               << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
639
4
  llvm::errs() << NumDirLookups << " dir lookups, "
640
4
               << NumDirCacheMisses << " dir cache misses.\n";
641
4
  llvm::errs() << NumFileLookups << " file lookups, "
642
4
               << NumFileCacheMisses << " file cache misses.\n";
643
644
  //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
645
4
}