Coverage Report

Created: 2021-09-21 08:58

/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
226k
      SeenFileEntries(64), NextFileUID(0) {
55
  // If the caller doesn't provide a virtual file system, just grab the real
56
  // file system.
57
226k
  if (!this->FS)
58
293
    this->FS = llvm::vfs::getRealFileSystem();
59
226k
}
60
61
220k
FileManager::~FileManager() = default;
62
63
14
void FileManager::setStatCache(std::unique_ptr<FileSystemStatCache> statCache) {
64
14
  assert(statCache && "No stat cache provided?");
65
0
  StatCache = std::move(statCache);
66
14
}
67
68
16.8k
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.95M
                     bool CacheFailure) {
75
3.95M
  if (Filename.empty())
76
0
    return llvm::errorCodeToError(
77
0
        make_error_code(std::errc::no_such_file_or_directory));
78
79
3.95M
  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.95M
  StringRef DirName = llvm::sys::path::parent_path(Filename);
83
  // Use the current directory if file has no path component.
84
3.95M
  if (DirName.empty())
85
85.1k
    DirName = ".";
86
87
3.95M
  return FileMgr.getDirectoryRef(DirName, CacheFailure);
88
3.95M
}
89
90
/// Add all ancestors of the given path (pointing to either a file or
91
/// a directory) as virtual directories.
92
14.2k
void FileManager::addAncestorsAsVirtualDirs(StringRef Path) {
93
14.2k
  StringRef DirName = llvm::sys::path::parent_path(Path);
94
14.2k
  if (DirName.empty())
95
7.36k
    DirName = ".";
96
97
14.2k
  auto &NamedDirEnt = *SeenDirEntries.insert(
98
14.2k
        {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.2k
  if (NamedDirEnt.second)
105
5.23k
    return;
106
107
  // Add the virtual directory to the cache.
108
9.05k
  auto UDE = std::make_unique<DirectoryEntry>();
109
9.05k
  UDE->Name = NamedDirEnt.first();
110
9.05k
  NamedDirEnt.second = *UDE.get();
111
9.05k
  VirtualDirectoryEntries.push_back(std::move(UDE));
112
113
  // Recursively add the other ancestors.
114
9.05k
  addAncestorsAsVirtualDirs(DirName);
115
9.05k
}
116
117
llvm::Expected<DirectoryEntryRef>
118
10.5M
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
10.5M
  if (DirName.size() > 1 &&
123
10.5M
      
DirName != llvm::sys::path::root_path(DirName)10.1M
&&
124
10.5M
      
llvm::sys::path::is_separator(DirName.back())10.1M
)
125
12.1k
    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_insensitive(llvm::sys::path::root_name(DirName))) {
132
    DirNameStr = DirName.str() + '.';
133
    DirName = DirNameStr;
134
  }
135
#endif
136
137
10.5M
  ++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
10.5M
  auto SeenDirInsertResult =
142
10.5M
      SeenDirEntries.insert({DirName, std::errc::no_such_file_or_directory});
143
10.5M
  if (!SeenDirInsertResult.second) {
144
9.47M
    if (SeenDirInsertResult.first->second)
145
7.99M
      return DirectoryEntryRef(*SeenDirInsertResult.first);
146
1.47M
    return llvm::errorCodeToError(SeenDirInsertResult.first->second.getError());
147
9.47M
  }
148
149
  // We've not seen this before. Fill it in.
150
1.12M
  ++NumDirCacheMisses;
151
1.12M
  auto &NamedDirEnt = *SeenDirInsertResult.first;
152
1.12M
  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
0
  StringRef InterndDirName = NamedDirEnt.first();
157
158
  // Check to see if the directory exists.
159
1.12M
  llvm::vfs::Status Status;
160
1.12M
  auto statError = getStatValue(InterndDirName, Status, false,
161
1.12M
                                nullptr /*directory lookup*/);
162
1.12M
  if (statError) {
163
    // There's no real directory at the given path.
164
666k
    if (CacheFailure)
165
665k
      NamedDirEnt.second = statError;
166
678
    else
167
678
      SeenDirEntries.erase(DirName);
168
666k
    return llvm::errorCodeToError(statError);
169
666k
  }
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
462k
  DirectoryEntry &UDE = UniqueRealDirs[Status.getUniqueID()];
176
177
462k
  NamedDirEnt.second = UDE;
178
462k
  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
459k
    UDE.Name  = InterndDirName;
182
459k
  }
183
184
462k
  return DirectoryEntryRef(NamedDirEnt);
185
1.12M
}
186
187
llvm::ErrorOr<const DirectoryEntry *>
188
6.40M
FileManager::getDirectory(StringRef DirName, bool CacheFailure) {
189
6.40M
  auto Result = getDirectoryRef(DirName, CacheFailure);
190
6.40M
  if (Result)
191
5.89M
    return &Result->getDirEntry();
192
508k
  return llvm::errorToErrorCode(Result.takeError());
193
6.40M
}
194
195
llvm::ErrorOr<const FileEntry *>
196
705k
FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) {
197
705k
  auto Result = getFileRef(Filename, openFile, CacheFailure);
198
705k
  if (Result)
199
517k
    return &Result->getFileEntry();
200
187k
  return llvm::errorToErrorCode(Result.takeError());
201
705k
}
202
203
llvm::Expected<FileEntryRef>
204
6.45M
FileManager::getFileRef(StringRef Filename, bool openFile, bool CacheFailure) {
205
6.45M
  ++NumFileLookups;
206
207
  // See if there is already an entry in the map.
208
6.45M
  auto SeenFileInsertResult =
209
6.45M
      SeenFileEntries.insert({Filename, std::errc::no_such_file_or_directory});
210
6.45M
  if (!SeenFileInsertResult.second) {
211
2.50M
    if (!SeenFileInsertResult.first->second)
212
59.2k
      return llvm::errorCodeToError(
213
59.2k
          SeenFileInsertResult.first->second.getError());
214
    // Construct and return and FileEntryRef, unless it's a redirect to another
215
    // filename.
216
2.45M
    FileEntryRef::MapValue Value = *SeenFileInsertResult.first->second;
217
2.45M
    if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
218
2.44M
      return FileEntryRef(*SeenFileInsertResult.first);
219
1.04k
    return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
220
1.04k
        Value.V.get<const void *>()));
221
2.45M
  }
222
223
  // We've not seen this before. Fill it in.
224
3.94M
  ++NumFileCacheMisses;
225
3.94M
  auto *NamedFileEnt = &*SeenFileInsertResult.first;
226
3.94M
  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
0
  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.94M
  auto DirInfoOrErr = getDirectoryFromFile(*this, Filename, CacheFailure);
238
3.94M
  if (!DirInfoOrErr) { // Directory doesn't exist, file can't exist.
239
1.56M
    std::error_code Err = errorToErrorCode(DirInfoOrErr.takeError());
240
1.56M
    if (CacheFailure)
241
1.56M
      NamedFileEnt->second = Err;
242
678
    else
243
678
      SeenFileEntries.erase(Filename);
244
245
1.56M
    return llvm::errorCodeToError(Err);
246
1.56M
  }
247
2.37M
  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.37M
  std::unique_ptr<llvm::vfs::File> F;
254
2.37M
  llvm::vfs::Status Status;
255
2.37M
  auto statError = getStatValue(InterndFileName, Status, true,
256
2.37M
                                openFile ? 
&F660k
:
nullptr1.71M
);
257
2.37M
  if (statError) {
258
    // There's no real file at the given path.
259
339k
    if (CacheFailure)
260
338k
      NamedFileEnt->second = statError;
261
884
    else
262
884
      SeenFileEntries.erase(Filename);
263
264
339k
    return llvm::errorCodeToError(statError);
265
339k
  }
266
267
2.03M
  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
0
  FileEntry &UFE = UniqueRealFiles[Status.getUniqueID()];
272
273
2.03M
  if (Status.getName() == Filename) {
274
    // The name matches. Set the FileEntry.
275
2.03M
    NamedFileEnt->second = FileEntryRef::MapValue(UFE, DirInfo);
276
2.03M
  } else {
277
    // Name mismatch. We need a redirect. First grab the actual entry we want
278
    // to return.
279
    //
280
    // This redirection logic intentionally leaks the external name of a
281
    // redirected file that uses 'use-external-name' in \a
282
    // vfs::RedirectionFileSystem. This allows clang to report the external
283
    // name to users (in diagnostics) and to tools that don't have access to
284
    // the VFS (in debug info and dependency '.d' files).
285
    //
286
    // FIXME: This is pretty complicated. It's also inconsistent with how
287
    // "real" filesystems behave and confuses parts of clang expect to see the
288
    // name-as-accessed on the \a FileEntryRef. Maybe the returned \a
289
    // FileEntryRef::getName() could return the accessed name unmodified, but
290
    // make the external name available via a separate API.
291
309
    auto &Redirection =
292
309
        *SeenFileEntries
293
309
             .insert({Status.getName(), FileEntryRef::MapValue(UFE, DirInfo)})
294
309
             .first;
295
309
    assert(Redirection.second->V.is<FileEntry *>() &&
296
309
           "filename redirected to a non-canonical filename?");
297
0
    assert(Redirection.second->V.get<FileEntry *>() == &UFE &&
298
309
           "filename from getStatValue() refers to wrong file");
299
300
    // Cache the redirection in the previously-inserted entry, still available
301
    // in the tentative return value.
302
0
    NamedFileEnt->second = FileEntryRef::MapValue(Redirection);
303
304
    // Fix the tentative return value.
305
309
    NamedFileEnt = &Redirection;
306
309
  }
307
308
0
  FileEntryRef ReturnedRef(*NamedFileEnt);
309
2.03M
  if (UFE.isValid()) { // Already have an entry with this inode, return it.
310
311
    // FIXME: this hack ensures that if we look up a file by a virtual path in
312
    // the VFS that the getDir() will have the virtual path, even if we found
313
    // the file by a 'real' path first. This is required in order to find a
314
    // module's structure when its headers/module map are mapped in the VFS.
315
    // We should remove this as soon as we can properly support a file having
316
    // multiple names.
317
5.78k
    if (&DirInfo.getDirEntry() != UFE.Dir && 
Status.IsVFSMapped3.01k
)
318
12
      UFE.Dir = &DirInfo.getDirEntry();
319
320
    // Always update LastRef to the last name by which a file was accessed.
321
    // FIXME: Neither this nor always using the first reference is correct; we
322
    // want to switch towards a design where we return a FileName object that
323
    // encapsulates both the name by which the file was accessed and the
324
    // corresponding FileEntry.
325
    // FIXME: LastRef should be removed from FileEntry once all clients adopt
326
    // FileEntryRef.
327
5.78k
    UFE.LastRef = ReturnedRef;
328
329
5.78k
    return ReturnedRef;
330
5.78k
  }
331
332
  // Otherwise, we don't have this file yet, add it.
333
2.03M
  UFE.LastRef = ReturnedRef;
334
2.03M
  UFE.Size    = Status.getSize();
335
2.03M
  UFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
336
2.03M
  UFE.Dir     = &DirInfo.getDirEntry();
337
2.03M
  UFE.UID     = NextFileUID++;
338
2.03M
  UFE.UniqueID = Status.getUniqueID();
339
2.03M
  UFE.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
340
2.03M
  UFE.File = std::move(F);
341
2.03M
  UFE.IsValid = true;
342
343
2.03M
  if (UFE.File) {
344
438k
    if (auto PathName = UFE.File->getName())
345
438k
      fillRealPathName(&UFE, *PathName);
346
1.59M
  } else 
if (1.59M
!openFile1.59M
) {
347
    // We should still fill the path even if we aren't opening the file.
348
1.59M
    fillRealPathName(&UFE, InterndFileName);
349
1.59M
  }
350
2.03M
  return ReturnedRef;
351
2.03M
}
352
353
667
llvm::Expected<FileEntryRef> FileManager::getSTDIN() {
354
  // Only read stdin once.
355
667
  if (STDIN)
356
0
    return *STDIN;
357
358
667
  std::unique_ptr<llvm::MemoryBuffer> Content;
359
667
  if (auto ContentOrError = llvm::MemoryBuffer::getSTDIN())
360
667
    Content = std::move(*ContentOrError);
361
0
  else
362
0
    return llvm::errorCodeToError(ContentOrError.getError());
363
364
667
  STDIN = getVirtualFileRef(Content->getBufferIdentifier(),
365
667
                            Content->getBufferSize(), 0);
366
667
  FileEntry &FE = const_cast<FileEntry &>(STDIN->getFileEntry());
367
667
  FE.Content = std::move(Content);
368
667
  FE.IsNamedPipe = true;
369
667
  return *STDIN;
370
667
}
371
372
const FileEntry *FileManager::getVirtualFile(StringRef Filename, off_t Size,
373
4.48k
                                             time_t ModificationTime) {
374
4.48k
  return &getVirtualFileRef(Filename, Size, ModificationTime).getFileEntry();
375
4.48k
}
376
377
FileEntryRef FileManager::getVirtualFileRef(StringRef Filename, off_t Size,
378
5.39k
                                            time_t ModificationTime) {
379
5.39k
  ++NumFileLookups;
380
381
  // See if there is already an entry in the map for an existing file.
382
5.39k
  auto &NamedFileEnt = *SeenFileEntries.insert(
383
5.39k
      {Filename, std::errc::no_such_file_or_directory}).first;
384
5.39k
  if (NamedFileEnt.second) {
385
169
    FileEntryRef::MapValue Value = *NamedFileEnt.second;
386
169
    if (LLVM_LIKELY(Value.V.is<FileEntry *>()))
387
169
      return FileEntryRef(NamedFileEnt);
388
0
    return FileEntryRef(*reinterpret_cast<const FileEntryRef::MapEntry *>(
389
0
        Value.V.get<const void *>()));
390
169
  }
391
392
  // We've not seen this before, or the file is cached as non-existent.
393
5.23k
  ++NumFileCacheMisses;
394
5.23k
  addAncestorsAsVirtualDirs(Filename);
395
5.23k
  FileEntry *UFE = nullptr;
396
397
  // Now that all ancestors of Filename are in the cache, the
398
  // following call is guaranteed to find the DirectoryEntry from the
399
  // cache. A virtual file can also have an empty filename, that could come
400
  // from a source location preprocessor directive with an empty filename as
401
  // an example, so we need to pretend it has a name to ensure a valid directory
402
  // entry can be returned.
403
5.23k
  auto DirInfo = expectedToOptional(getDirectoryFromFile(
404
5.23k
      *this, Filename.empty() ? 
"."1
:
Filename5.22k
, /*CacheFailure=*/true));
405
5.23k
  assert(DirInfo &&
406
5.23k
         "The directory of a virtual file should already be in the cache.");
407
408
  // Check to see if the file exists. If so, drop the virtual file
409
0
  llvm::vfs::Status Status;
410
5.23k
  const char *InterndFileName = NamedFileEnt.first().data();
411
5.23k
  if (!getStatValue(InterndFileName, Status, true, nullptr)) {
412
2.63k
    UFE = &UniqueRealFiles[Status.getUniqueID()];
413
2.63k
    Status = llvm::vfs::Status(
414
2.63k
      Status.getName(), Status.getUniqueID(),
415
2.63k
      llvm::sys::toTimePoint(ModificationTime),
416
2.63k
      Status.getUser(), Status.getGroup(), Size,
417
2.63k
      Status.getType(), Status.getPermissions());
418
419
2.63k
    NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo);
420
421
    // If we had already opened this file, close it now so we don't
422
    // leak the descriptor. We're not going to use the file
423
    // descriptor anyway, since this is a virtual file.
424
2.63k
    if (UFE->File)
425
0
      UFE->closeFile();
426
427
    // If we already have an entry with this inode, return it.
428
    //
429
    // FIXME: Surely this should add a reference by the new name, and return
430
    // it instead...
431
2.63k
    if (UFE->isValid())
432
1
      return FileEntryRef(NamedFileEnt);
433
434
2.63k
    UFE->UniqueID = Status.getUniqueID();
435
2.63k
    UFE->IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file;
436
2.63k
    fillRealPathName(UFE, Status.getName());
437
2.63k
  } else {
438
2.59k
    VirtualFileEntries.push_back(std::make_unique<FileEntry>());
439
2.59k
    UFE = VirtualFileEntries.back().get();
440
2.59k
    NamedFileEnt.second = FileEntryRef::MapValue(*UFE, *DirInfo);
441
2.59k
  }
442
443
5.22k
  UFE->LastRef = FileEntryRef(NamedFileEnt);
444
5.22k
  UFE->Size    = Size;
445
5.22k
  UFE->ModTime = ModificationTime;
446
5.22k
  UFE->Dir     = &DirInfo->getDirEntry();
447
5.22k
  UFE->UID     = NextFileUID++;
448
5.22k
  UFE->IsValid = true;
449
5.22k
  UFE->File.reset();
450
5.22k
  return FileEntryRef(NamedFileEnt);
451
5.23k
}
452
453
2
llvm::Optional<FileEntryRef> FileManager::getBypassFile(FileEntryRef VF) {
454
  // Stat of the file and return nullptr if it doesn't exist.
455
2
  llvm::vfs::Status Status;
456
2
  if (getStatValue(VF.getName(), Status, /*isFile=*/true, /*F=*/nullptr))
457
0
    return None;
458
459
2
  if (!SeenBypassFileEntries)
460
2
    SeenBypassFileEntries = std::make_unique<
461
2
        llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>>>();
462
463
  // If we've already bypassed just use the existing one.
464
2
  auto Insertion = SeenBypassFileEntries->insert(
465
2
      {VF.getName(), std::errc::no_such_file_or_directory});
466
2
  if (!Insertion.second)
467
0
    return FileEntryRef(*Insertion.first);
468
469
  // Fill in the new entry from the stat.
470
2
  BypassFileEntries.push_back(std::make_unique<FileEntry>());
471
2
  const FileEntry &VFE = VF.getFileEntry();
472
2
  FileEntry &BFE = *BypassFileEntries.back();
473
2
  Insertion.first->second = FileEntryRef::MapValue(BFE, VF.getDir());
474
2
  BFE.LastRef = FileEntryRef(*Insertion.first);
475
2
  BFE.Size = Status.getSize();
476
2
  BFE.Dir = VFE.Dir;
477
2
  BFE.ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
478
2
  BFE.UID = NextFileUID++;
479
2
  BFE.IsValid = true;
480
481
  // Save the entry in the bypass table and return.
482
2
  return FileEntryRef(*Insertion.first);
483
2
}
484
485
2.16M
bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const {
486
2.16M
  StringRef pathRef(path.data(), path.size());
487
488
2.16M
  if (FileSystemOpts.WorkingDir.empty()
489
2.16M
      || 
llvm::sys::path::is_absolute(pathRef)8.83k
)
490
2.15M
    return false;
491
492
977
  SmallString<128> NewPath(FileSystemOpts.WorkingDir);
493
977
  llvm::sys::path::append(NewPath, pathRef);
494
977
  path = NewPath;
495
977
  return true;
496
2.16M
}
497
498
2.13M
bool FileManager::makeAbsolutePath(SmallVectorImpl<char> &Path) const {
499
2.13M
  bool Changed = FixupRelativePath(Path);
500
501
2.13M
  if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
502
98.3k
    FS->makeAbsolute(Path);
503
98.3k
    Changed = true;
504
98.3k
  }
505
506
2.13M
  return Changed;
507
2.13M
}
508
509
2.03M
void FileManager::fillRealPathName(FileEntry *UFE, llvm::StringRef FileName) {
510
2.03M
  llvm::SmallString<128> AbsPath(FileName);
511
  // This is not the same as `VFS::getRealPath()`, which resolves symlinks
512
  // but can be very expensive on real file systems.
513
  // FIXME: the semantic of RealPathName is unclear, and the name might be
514
  // misleading. We need to clean up the interface here.
515
2.03M
  makeAbsolutePath(AbsPath);
516
2.03M
  llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
517
2.03M
  UFE->RealPathName = std::string(AbsPath.str());
518
2.03M
}
519
520
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
521
FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile,
522
700k
                              bool RequiresNullTerminator) {
523
  // If the content is living on the file entry, return a reference to it.
524
700k
  if (Entry->Content)
525
667
    return llvm::MemoryBuffer::getMemBuffer(Entry->Content->getMemBufferRef());
526
527
700k
  uint64_t FileSize = Entry->getSize();
528
  // If there's a high enough chance that the file have changed since we
529
  // got its size, force a stat before opening it.
530
700k
  if (isVolatile || 
Entry->isNamedPipe()682k
)
531
18.0k
    FileSize = -1;
532
533
700k
  StringRef Filename = Entry->getName();
534
  // If the file is already open, use the open file descriptor.
535
700k
  if (Entry->File) {
536
435k
    auto Result = Entry->File->getBuffer(Filename, FileSize,
537
435k
                                         RequiresNullTerminator, isVolatile);
538
435k
    Entry->closeFile();
539
435k
    return Result;
540
435k
  }
541
542
  // Otherwise, open the file.
543
264k
  return getBufferForFileImpl(Filename, FileSize, isVolatile,
544
264k
                              RequiresNullTerminator);
545
700k
}
546
547
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
548
FileManager::getBufferForFileImpl(StringRef Filename, int64_t FileSize,
549
                                  bool isVolatile,
550
268k
                                  bool RequiresNullTerminator) {
551
268k
  if (FileSystemOpts.WorkingDir.empty())
552
268k
    return FS->getBufferForFile(Filename, FileSize, RequiresNullTerminator,
553
268k
                                isVolatile);
554
555
414
  SmallString<128> FilePath(Filename);
556
414
  FixupRelativePath(FilePath);
557
414
  return FS->getBufferForFile(FilePath, FileSize, RequiresNullTerminator,
558
414
                              isVolatile);
559
268k
}
560
561
/// getStatValue - Get the 'stat' information for the specified path,
562
/// using the cache to accelerate it if possible.  This returns true
563
/// if the path points to a virtual file or does not exist, or returns
564
/// false if it's an existent real file.  If FileDescriptor is NULL,
565
/// do directory look-up instead of file look-up.
566
std::error_code
567
FileManager::getStatValue(StringRef Path, llvm::vfs::Status &Status,
568
3.51M
                          bool isFile, std::unique_ptr<llvm::vfs::File> *F) {
569
  // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be
570
  // absolute!
571
3.51M
  if (FileSystemOpts.WorkingDir.empty())
572
3.50M
    return FileSystemStatCache::get(Path, Status, isFile, F,
573
3.50M
                                    StatCache.get(), *FS);
574
575
5.35k
  SmallString<128> FilePath(Path);
576
5.35k
  FixupRelativePath(FilePath);
577
578
5.35k
  return FileSystemStatCache::get(FilePath.c_str(), Status, isFile, F,
579
5.35k
                                  StatCache.get(), *FS);
580
3.51M
}
581
582
std::error_code
583
FileManager::getNoncachedStatValue(StringRef Path,
584
12.6k
                                   llvm::vfs::Status &Result) {
585
12.6k
  SmallString<128> FilePath(Path);
586
12.6k
  FixupRelativePath(FilePath);
587
588
12.6k
  llvm::ErrorOr<llvm::vfs::Status> S = FS->status(FilePath.c_str());
589
12.6k
  if (!S)
590
12.6k
    return S.getError();
591
8
  Result = *S;
592
8
  return std::error_code();
593
12.6k
}
594
595
void FileManager::GetUniqueIDMapping(
596
5.32k
                   SmallVectorImpl<const FileEntry *> &UIDToFiles) const {
597
5.32k
  UIDToFiles.clear();
598
5.32k
  UIDToFiles.resize(NextFileUID);
599
600
  // Map file entries
601
5.32k
  for (llvm::StringMap<llvm::ErrorOr<FileEntryRef::MapValue>,
602
5.32k
                       llvm::BumpPtrAllocator>::const_iterator
603
5.32k
           FE = SeenFileEntries.begin(),
604
5.32k
           FEEnd = SeenFileEntries.end();
605
789k
       FE != FEEnd; 
++FE784k
)
606
784k
    if (llvm::ErrorOr<FileEntryRef::MapValue> Entry = FE->getValue()) {
607
332k
      if (const auto *FE = Entry->V.dyn_cast<FileEntry *>())
608
332k
        UIDToFiles[FE->getUID()] = FE;
609
332k
    }
610
611
  // Map virtual file entries
612
5.32k
  for (const auto &VFE : VirtualFileEntries)
613
444
    UIDToFiles[VFE->getUID()] = VFE.get();
614
5.32k
}
615
616
365k
StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
617
365k
  llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
618
365k
    = CanonicalNames.find(Dir);
619
365k
  if (Known != CanonicalNames.end())
620
352k
    return Known->second;
621
622
12.8k
  StringRef CanonicalName(Dir->getName());
623
624
12.8k
  SmallString<4096> CanonicalNameBuf;
625
12.8k
  if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
626
12.8k
    CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage);
627
628
12.8k
  CanonicalNames.insert({Dir, CanonicalName});
629
12.8k
  return CanonicalName;
630
365k
}
631
632
3
StringRef FileManager::getCanonicalName(const FileEntry *File) {
633
3
  llvm::DenseMap<const void *, llvm::StringRef>::iterator Known
634
3
    = CanonicalNames.find(File);
635
3
  if (Known != CanonicalNames.end())
636
1
    return Known->second;
637
638
2
  StringRef CanonicalName(File->getName());
639
640
2
  SmallString<4096> CanonicalNameBuf;
641
2
  if (!FS->getRealPath(File->getName(), CanonicalNameBuf))
642
2
    CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage);
643
644
2
  CanonicalNames.insert({File, CanonicalName});
645
2
  return CanonicalName;
646
3
}
647
648
4
void FileManager::PrintStats() const {
649
4
  llvm::errs() << "\n*** File Manager Stats:\n";
650
4
  llvm::errs() << UniqueRealFiles.size() << " real files found, "
651
4
               << UniqueRealDirs.size() << " real dirs found.\n";
652
4
  llvm::errs() << VirtualFileEntries.size() << " virtual files found, "
653
4
               << VirtualDirectoryEntries.size() << " virtual dirs found.\n";
654
4
  llvm::errs() << NumDirLookups << " dir lookups, "
655
4
               << NumDirCacheMisses << " dir cache misses.\n";
656
4
  llvm::errs() << NumFileLookups << " file lookups, "
657
4
               << NumFileCacheMisses << " file cache misses.\n";
658
659
  //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
660
4
}