Coverage Report

Created: 2020-09-22 08:39

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Frontend/PrecompiledPreamble.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- PrecompiledPreamble.cpp - Build precompiled preambles --*- C++ -*-===//
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
// Helper class to build precompiled preamble.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Frontend/PrecompiledPreamble.h"
14
#include "clang/AST/DeclObjC.h"
15
#include "clang/Basic/FileManager.h"
16
#include "clang/Basic/LangStandard.h"
17
#include "clang/Basic/TargetInfo.h"
18
#include "clang/Frontend/CompilerInstance.h"
19
#include "clang/Frontend/CompilerInvocation.h"
20
#include "clang/Frontend/FrontendActions.h"
21
#include "clang/Frontend/FrontendOptions.h"
22
#include "clang/Lex/HeaderSearch.h"
23
#include "clang/Lex/Lexer.h"
24
#include "clang/Lex/Preprocessor.h"
25
#include "clang/Lex/PreprocessorOptions.h"
26
#include "clang/Serialization/ASTWriter.h"
27
#include "llvm/ADT/SmallString.h"
28
#include "llvm/ADT/StringExtras.h"
29
#include "llvm/ADT/StringSet.h"
30
#include "llvm/ADT/iterator_range.h"
31
#include "llvm/Config/llvm-config.h"
32
#include "llvm/Support/CrashRecoveryContext.h"
33
#include "llvm/Support/FileSystem.h"
34
#include "llvm/Support/Path.h"
35
#include "llvm/Support/Process.h"
36
#include "llvm/Support/VirtualFileSystem.h"
37
#include <limits>
38
#include <mutex>
39
#include <utility>
40
41
using namespace clang;
42
43
namespace {
44
45
0
StringRef getInMemoryPreamblePath() {
46
0
#if defined(LLVM_ON_UNIX)
47
0
  return "/__clang_tmp/___clang_inmemory_preamble___";
48
#elif defined(_WIN32)
49
  return "C:\\__clang_tmp\\___clang_inmemory_preamble___";
50
#else
51
#warning "Unknown platform. Defaulting to UNIX-style paths for in-memory PCHs"
52
  return "/__clang_tmp/___clang_inmemory_preamble___";
53
#endif
54
0
}
55
56
IntrusiveRefCntPtr<llvm::vfs::FileSystem>
57
createVFSOverlayForPreamblePCH(StringRef PCHFilename,
58
                               std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,
59
13
                               IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
60
  // We want only the PCH file from the real filesystem to be available,
61
  // so we create an in-memory VFS with just that and overlay it on top.
62
13
  IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> PCHFS(
63
13
      new llvm::vfs::InMemoryFileSystem());
64
13
  PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer));
65
13
  IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> Overlay(
66
13
      new llvm::vfs::OverlayFileSystem(VFS));
67
13
  Overlay->pushOverlay(PCHFS);
68
13
  return Overlay;
69
13
}
70
71
class PreambleDependencyCollector : public DependencyCollector {
72
public:
73
  // We want to collect all dependencies for correctness. Avoiding the real
74
  // system dependencies (e.g. stl from /usr/lib) would probably be a good idea,
75
  // but there is no way to distinguish between those and the ones that can be
76
  // spuriously added by '-isystem' (e.g. to suppress warnings from those
77
  // headers).
78
292
  bool needSystemDependencies() override { return true; }
79
};
80
81
// Collects files whose existence would invalidate the preamble.
82
// Collecting *all* of these would make validating it too slow though, so we
83
// just find all the candidates for 'file not found' diagnostics.
84
//
85
// A caveat that may be significant for generated files: we'll omit files under
86
// search path entries whose roots don't exist when the preamble is built.
87
// These are pruned by InitHeaderSearch and so we don't see the search path.
88
// It would be nice to include them but we don't want to duplicate all the rest
89
// of the InitHeaderSearch logic to reconstruct them.
90
class MissingFileCollector : public PPCallbacks {
91
  llvm::StringSet<> &Out;
92
  const HeaderSearch &Search;
93
  const SourceManager &SM;
94
95
public:
96
  MissingFileCollector(llvm::StringSet<> &Out, const HeaderSearch &Search,
97
                       const SourceManager &SM)
98
89
      : Out(Out), Search(Search), SM(SM) {}
99
100
  void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
101
                          StringRef FileName, bool IsAngled,
102
                          CharSourceRange FilenameRange, const FileEntry *File,
103
                          StringRef SearchPath, StringRef RelativePath,
104
                          const Module *Imported,
105
95
                          SrcMgr::CharacteristicKind FileType) override {
106
    // File is null if it wasn't found.
107
    // (We have some false negatives if PP recovered e.g. <foo> -> "foo")
108
95
    if (File != nullptr)
109
94
      return;
110
111
    // If it's a rare absolute include, we know the full path already.
112
1
    if (llvm::sys::path::is_absolute(FileName)) {
113
0
      Out.insert(FileName);
114
0
      return;
115
0
    }
116
117
    // Reconstruct the filenames that would satisfy this directive...
118
1
    llvm::SmallString<256> Buf;
119
3
    auto NotFoundRelativeTo = [&](const DirectoryEntry *DE) {
120
3
      Buf = DE->getName();
121
3
      llvm::sys::path::append(Buf, FileName);
122
3
      llvm::sys::path::remove_dots(Buf, /*remove_dot_dot=*/true);
123
3
      Out.insert(Buf);
124
3
    };
125
    // ...relative to the including file.
126
1
    if (!IsAngled) {
127
1
      if (const FileEntry *IncludingFile =
128
1
              SM.getFileEntryForID(SM.getFileID(IncludeTok.getLocation())))
129
1
        if (IncludingFile->getDir())
130
1
          NotFoundRelativeTo(IncludingFile->getDir());
131
1
    }
132
    // ...relative to the search paths.
133
1
    for (const auto &Dir : llvm::make_range(
134
1
             IsAngled ? 
Search.angled_dir_begin()0
: Search.search_dir_begin(),
135
3
             Search.search_dir_end())) {
136
      // No support for frameworks or header maps yet.
137
3
      if (Dir.isNormalDir())
138
2
        NotFoundRelativeTo(Dir.getDir());
139
3
    }
140
1
  }
141
};
142
143
/// Keeps a track of files to be deleted in destructor.
144
class TemporaryFiles {
145
public:
146
  // A static instance to be used by all clients.
147
  static TemporaryFiles &getInstance();
148
149
private:
150
  // Disallow constructing the class directly.
151
82
  TemporaryFiles() = default;
152
  // Disallow copy.
153
  TemporaryFiles(const TemporaryFiles &) = delete;
154
155
public:
156
  ~TemporaryFiles();
157
158
  /// Adds \p File to a set of tracked files.
159
  void addFile(StringRef File);
160
161
  /// Remove \p File from disk and from the set of tracked files.
162
  void removeFile(StringRef File);
163
164
private:
165
  std::mutex Mutex;
166
  llvm::StringSet<> Files;
167
};
168
169
177
TemporaryFiles &TemporaryFiles::getInstance() {
170
177
  static TemporaryFiles Instance;
171
177
  return Instance;
172
177
}
173
174
82
TemporaryFiles::~TemporaryFiles() {
175
82
  std::lock_guard<std::mutex> Guard(Mutex);
176
82
  for (const auto &File : Files)
177
1
    llvm::sys::fs::remove(File.getKey());
178
82
}
179
180
89
void TemporaryFiles::addFile(StringRef File) {
181
89
  std::lock_guard<std::mutex> Guard(Mutex);
182
89
  auto IsInserted = Files.insert(File).second;
183
89
  (void)IsInserted;
184
89
  assert(IsInserted && "File has already been added");
185
89
}
186
187
88
void TemporaryFiles::removeFile(StringRef File) {
188
88
  std::lock_guard<std::mutex> Guard(Mutex);
189
88
  auto WasPresent = Files.erase(File);
190
88
  (void)WasPresent;
191
88
  assert(WasPresent && "File was not tracked");
192
88
  llvm::sys::fs::remove(File);
193
88
}
194
195
class PrecompilePreambleAction : public ASTFrontendAction {
196
public:
197
  PrecompilePreambleAction(std::string *InMemStorage,
198
                           PreambleCallbacks &Callbacks)
199
89
      : InMemStorage(InMemStorage), Callbacks(Callbacks) {}
200
201
  std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
202
                                                 StringRef InFile) override;
203
204
178
  bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
205
206
89
  void setEmittedPreamblePCH(ASTWriter &Writer) {
207
89
    this->HasEmittedPreamblePCH = true;
208
89
    Callbacks.AfterPCHEmitted(Writer);
209
89
  }
210
211
89
  bool BeginSourceFileAction(CompilerInstance &CI) override {
212
89
    assert(CI.getLangOpts().CompilingPCH);
213
89
    return ASTFrontendAction::BeginSourceFileAction(CI);
214
89
  }
215
216
89
  bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
217
89
  bool hasCodeCompletionSupport() const override { return false; }
218
0
  bool hasASTFileSupport() const override { return false; }
219
178
  TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
220
221
private:
222
  friend class PrecompilePreambleConsumer;
223
224
  bool HasEmittedPreamblePCH = false;
225
  std::string *InMemStorage;
226
  PreambleCallbacks &Callbacks;
227
};
228
229
class PrecompilePreambleConsumer : public PCHGenerator {
230
public:
231
  PrecompilePreambleConsumer(PrecompilePreambleAction &Action,
232
                             const Preprocessor &PP,
233
                             InMemoryModuleCache &ModuleCache,
234
                             StringRef isysroot,
235
                             std::unique_ptr<raw_ostream> Out)
236
      : PCHGenerator(PP, ModuleCache, "", isysroot,
237
                     std::make_shared<PCHBuffer>(),
238
                     ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
239
                     /*AllowASTWithErrors=*/true),
240
89
        Action(Action), Out(std::move(Out)) {}
241
242
87
  bool HandleTopLevelDecl(DeclGroupRef DG) override {
243
87
    Action.Callbacks.HandleTopLevelDecl(DG);
244
87
    return true;
245
87
  }
246
247
89
  void HandleTranslationUnit(ASTContext &Ctx) override {
248
89
    PCHGenerator::HandleTranslationUnit(Ctx);
249
89
    if (!hasEmittedPCH())
250
0
      return;
251
252
    // Write the generated bitstream to "Out".
253
89
    *Out << getPCH();
254
    // Make sure it hits disk now.
255
89
    Out->flush();
256
    // Free the buffer.
257
89
    llvm::SmallVector<char, 0> Empty;
258
89
    getPCH() = std::move(Empty);
259
260
89
    Action.setEmittedPreamblePCH(getWriter());
261
89
  }
262
263
1
  bool shouldSkipFunctionBody(Decl *D) override {
264
1
    return Action.Callbacks.shouldSkipFunctionBody(D);
265
1
  }
266
267
private:
268
  PrecompilePreambleAction &Action;
269
  std::unique_ptr<raw_ostream> Out;
270
};
271
272
std::unique_ptr<ASTConsumer>
273
PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
274
89
                                            StringRef InFile) {
275
89
  std::string Sysroot;
276
89
  if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
277
0
    return nullptr;
278
279
89
  std::unique_ptr<llvm::raw_ostream> OS;
280
89
  if (InMemStorage) {
281
0
    OS = std::make_unique<llvm::raw_string_ostream>(*InMemStorage);
282
89
  } else {
283
89
    std::string OutputFile;
284
89
    OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
285
89
  }
286
89
  if (!OS)
287
0
    return nullptr;
288
289
89
  if (!CI.getFrontendOpts().RelocatablePCH)
290
89
    Sysroot.clear();
291
292
89
  return std::make_unique<PrecompilePreambleConsumer>(
293
89
      *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, std::move(OS));
294
89
}
295
296
465
template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
297
465
  if (!Val)
298
2
    return false;
299
463
  Output = std::move(*Val);
300
463
  return true;
301
463
}
302
303
} // namespace
304
305
PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
306
                                            const llvm::MemoryBuffer *Buffer,
307
510
                                            unsigned MaxLines) {
308
510
  return Lexer::ComputePreamble(Buffer->getBuffer(), LangOpts, MaxLines);
309
510
}
310
311
llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
312
    const CompilerInvocation &Invocation,
313
    const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
314
    DiagnosticsEngine &Diagnostics,
315
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
316
    std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
317
89
    PreambleCallbacks &Callbacks) {
318
89
  assert(VFS && "VFS is null");
319
320
89
  auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
321
89
  FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
322
89
  PreprocessorOptions &PreprocessorOpts =
323
89
      PreambleInvocation->getPreprocessorOpts();
324
325
89
  llvm::Optional<TempPCHFile> TempFile;
326
89
  if (!StoreInMemory) {
327
    // Create a temporary file for the precompiled preamble. In rare
328
    // circumstances, this can fail.
329
89
    llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> PreamblePCHFile =
330
89
        PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile();
331
89
    if (!PreamblePCHFile)
332
0
      return BuildPreambleError::CouldntCreateTempFile;
333
89
    TempFile = std::move(*PreamblePCHFile);
334
89
  }
335
336
89
  PCHStorage Storage = StoreInMemory ? 
PCHStorage(InMemoryPreamble())0
337
89
                                     : PCHStorage(std::move(*TempFile));
338
339
  // Save the preamble text for later; we'll need to compare against it for
340
  // subsequent reparses.
341
89
  std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
342
89
                                  MainFileBuffer->getBufferStart() +
343
89
                                      Bounds.Size);
344
89
  bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
345
346
  // Tell the compiler invocation to generate a temporary precompiled header.
347
89
  FrontendOpts.ProgramAction = frontend::GeneratePCH;
348
89
  FrontendOpts.OutputFile =
349
0
      std::string(StoreInMemory ? getInMemoryPreamblePath()
350
89
                                : Storage.asFile().getFilePath());
351
89
  PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
352
89
  PreprocessorOpts.PrecompiledPreambleBytes.second = false;
353
  // Inform preprocessor to record conditional stack when building the preamble.
354
89
  PreprocessorOpts.GeneratePreamble = true;
355
356
  // Create the compiler instance to use for building the precompiled preamble.
357
89
  std::unique_ptr<CompilerInstance> Clang(
358
89
      new CompilerInstance(std::move(PCHContainerOps)));
359
360
  // Recover resources if we crash before exiting this method.
361
89
  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
362
89
      Clang.get());
363
364
89
  Clang->setInvocation(std::move(PreambleInvocation));
365
89
  Clang->setDiagnostics(&Diagnostics);
366
367
  // Create the target instance.
368
89
  Clang->setTarget(TargetInfo::CreateTargetInfo(
369
89
      Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
370
89
  if (!Clang->hasTarget())
371
0
    return BuildPreambleError::CouldntCreateTargetInfo;
372
373
  // Inform the target of the language options.
374
  //
375
  // FIXME: We shouldn't need to do this, the target should be immutable once
376
  // created. This complexity should be lifted elsewhere.
377
89
  Clang->getTarget().adjust(Clang->getLangOpts());
378
379
89
  if (Clang->getFrontendOpts().Inputs.size() != 1 ||
380
89
      Clang->getFrontendOpts().Inputs[0].getKind().getFormat() !=
381
89
          InputKind::Source ||
382
89
      Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() ==
383
0
          Language::LLVM_IR) {
384
0
    return BuildPreambleError::BadInputs;
385
0
  }
386
387
  // Clear out old caches and data.
388
89
  Diagnostics.Reset();
389
89
  ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
390
391
89
  VFS =
392
89
      createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
393
394
  // Create a file manager object to provide access to and cache the filesystem.
395
89
  Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
396
397
  // Create the source manager.
398
89
  Clang->setSourceManager(
399
89
      new SourceManager(Diagnostics, Clang->getFileManager()));
400
401
89
  auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>();
402
89
  Clang->addDependencyCollector(PreambleDepCollector);
403
404
89
  Clang->getLangOpts().CompilingPCH = true;
405
406
  // Remap the main source file to the preamble buffer.
407
89
  StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
408
89
  auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
409
89
      MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
410
89
  if (PreprocessorOpts.RetainRemappedFileBuffers) {
411
    // MainFileBuffer will be deleted by unique_ptr after leaving the method.
412
89
    PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
413
0
  } else {
414
    // In that case, remapped buffer will be deleted by CompilerInstance on
415
    // BeginSourceFile, so we call release() to avoid double deletion.
416
0
    PreprocessorOpts.addRemappedFile(MainFilePath,
417
0
                                     PreambleInputBuffer.release());
418
0
  }
419
420
89
  std::unique_ptr<PrecompilePreambleAction> Act;
421
89
  Act.reset(new PrecompilePreambleAction(
422
89
      StoreInMemory ? 
&Storage.asMemory().Data0
: nullptr, Callbacks));
423
89
  Callbacks.BeforeExecute(*Clang);
424
89
  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
425
0
    return BuildPreambleError::BeginSourceFileFailed;
426
427
89
  std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
428
89
      Callbacks.createPPCallbacks();
429
89
  if (DelegatedPPCallbacks)
430
89
    Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
431
89
  if (auto CommentHandler = Callbacks.getCommentHandler())
432
0
    Clang->getPreprocessor().addCommentHandler(CommentHandler);
433
89
  llvm::StringSet<> MissingFiles;
434
89
  Clang->getPreprocessor().addPPCallbacks(
435
89
      std::make_unique<MissingFileCollector>(
436
89
          MissingFiles, Clang->getPreprocessor().getHeaderSearchInfo(),
437
89
          Clang->getSourceManager()));
438
439
89
  if (llvm::Error Err = Act->Execute())
440
0
    return errorToErrorCode(std::move(Err));
441
442
  // Run the callbacks.
443
89
  Callbacks.AfterExecute(*Clang);
444
445
89
  Act->EndSourceFile();
446
447
89
  if (!Act->hasEmittedPreamblePCH())
448
0
    return BuildPreambleError::CouldntEmitPCH;
449
450
  // Keep track of all of the files that the source manager knows about,
451
  // so we can verify whether they have changed or not.
452
89
  llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
453
454
89
  SourceManager &SourceMgr = Clang->getSourceManager();
455
247
  for (auto &Filename : PreambleDepCollector->getDependencies()) {
456
247
    auto FileOrErr = Clang->getFileManager().getFile(Filename);
457
247
    if (!FileOrErr ||
458
246
        *FileOrErr == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
459
90
      continue;
460
157
    auto File = *FileOrErr;
461
157
    if (time_t ModTime = File->getModificationTime()) {
462
147
      FilesInPreamble[File->getName()] =
463
147
          PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
464
147
                                                               ModTime);
465
10
    } else {
466
10
      const llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
467
10
      FilesInPreamble[File->getName()] =
468
10
          PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
469
10
    }
470
157
  }
471
472
89
  return PrecompiledPreamble(
473
89
      std::move(Storage), std::move(PreambleBytes), PreambleEndsAtStartOfLine,
474
89
      std::move(FilesInPreamble), std::move(MissingFiles));
475
89
}
476
477
539
PreambleBounds PrecompiledPreamble::getBounds() const {
478
539
  return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
479
539
}
480
481
0
std::size_t PrecompiledPreamble::getSize() const {
482
0
  switch (Storage.getKind()) {
483
0
  case PCHStorage::Kind::Empty:
484
0
    assert(false && "Calling getSize() on invalid PrecompiledPreamble. "
485
0
                    "Was it std::moved?");
486
0
    return 0;
487
0
  case PCHStorage::Kind::InMemory:
488
0
    return Storage.asMemory().Data.size();
489
0
  case PCHStorage::Kind::TempFile: {
490
0
    uint64_t Result;
491
0
    if (llvm::sys::fs::file_size(Storage.asFile().getFilePath(), Result))
492
0
      return 0;
493
494
0
    assert(Result <= std::numeric_limits<std::size_t>::max() &&
495
0
           "file size did not fit into size_t");
496
0
    return Result;
497
0
  }
498
0
  }
499
0
  llvm_unreachable("Unhandled storage kind");
500
0
}
501
502
bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation,
503
                                   const llvm::MemoryBuffer *MainFileBuffer,
504
                                   PreambleBounds Bounds,
505
251
                                   llvm::vfs::FileSystem *VFS) const {
506
507
251
  assert(
508
251
      Bounds.Size <= MainFileBuffer->getBufferSize() &&
509
251
      "Buffer is too large. Bounds were calculated from a different buffer?");
510
511
251
  auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
512
251
  PreprocessorOptions &PreprocessorOpts =
513
251
      PreambleInvocation->getPreprocessorOpts();
514
515
  // We've previously computed a preamble. Check whether we have the same
516
  // preamble now that we did before, and that there's enough space in
517
  // the main-file buffer within the precompiled preamble to fit the
518
  // new main file.
519
251
  if (PreambleBytes.size() != Bounds.Size ||
520
245
      PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
521
245
      !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
522
245
                  MainFileBuffer->getBuffer().begin()))
523
6
    return false;
524
  // The preamble has not changed. We may be able to re-use the precompiled
525
  // preamble.
526
527
  // Check that none of the files used by the preamble have changed.
528
  // First, make a record of those files that have been overridden via
529
  // remapping or unsaved_files.
530
245
  std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
531
245
  llvm::StringSet<> OverriddenAbsPaths; // Either by buffers or files.
532
0
  for (const auto &R : PreprocessorOpts.RemappedFiles) {
533
0
    llvm::vfs::Status Status;
534
0
    if (!moveOnNoError(VFS->status(R.second), Status)) {
535
      // If we can't stat the file we're remapping to, assume that something
536
      // horrible happened.
537
0
      return false;
538
0
    }
539
    // If a mapped file was previously missing, then it has changed.
540
0
    llvm::SmallString<128> MappedPath(R.first);
541
0
    if (!VFS->makeAbsolute(MappedPath))
542
0
      OverriddenAbsPaths.insert(MappedPath);
543
544
0
    OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
545
0
        Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
546
0
  }
547
548
  // OverridenFileBuffers tracks only the files not found in VFS.
549
245
  llvm::StringMap<PreambleFileHash> OverridenFileBuffers;
550
6
  for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
551
6
    const PrecompiledPreamble::PreambleFileHash PreambleHash =
552
6
        PreambleFileHash::createForMemoryBuffer(RB.second);
553
6
    llvm::vfs::Status Status;
554
6
    if (moveOnNoError(VFS->status(RB.first), Status))
555
4
      OverriddenFiles[Status.getUniqueID()] = PreambleHash;
556
2
    else
557
2
      OverridenFileBuffers[RB.first] = PreambleHash;
558
559
6
    llvm::SmallString<128> MappedPath(RB.first);
560
6
    if (!VFS->makeAbsolute(MappedPath))
561
6
      OverriddenAbsPaths.insert(MappedPath);
562
6
  }
563
564
  // Check whether anything has changed.
565
461
  for (const auto &F : FilesInPreamble) {
566
461
    auto OverridenFileBuffer = OverridenFileBuffers.find(F.first());
567
461
    if (OverridenFileBuffer != OverridenFileBuffers.end()) {
568
      // The file's buffer was remapped and the file was not found in VFS.
569
      // Check whether it matches up with the previous mapping.
570
2
      if (OverridenFileBuffer->second != F.second)
571
0
        return false;
572
2
      continue;
573
2
    }
574
575
459
    llvm::vfs::Status Status;
576
459
    if (!moveOnNoError(VFS->status(F.first()), Status)) {
577
      // If the file's buffer is not remapped and we can't stat it,
578
      // assume that something horrible happened.
579
0
      return false;
580
0
    }
581
582
459
    std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
583
459
        OverriddenFiles.find(Status.getUniqueID());
584
459
    if (Overridden != OverriddenFiles.end()) {
585
      // This file was remapped; check whether the newly-mapped file
586
      // matches up with the previous mapping.
587
4
      if (Overridden->second != F.second)
588
2
        return false;
589
2
      continue;
590
2
    }
591
592
    // Neither the file's buffer nor the file itself was remapped;
593
    // check whether it has changed on disk.
594
455
    if (Status.getSize() != uint64_t(F.second.Size) ||
595
453
        llvm::sys::toTimeT(Status.getLastModificationTime()) !=
596
453
            F.second.ModTime)
597
2
      return false;
598
455
  }
599
241
  for (const auto &F : MissingFiles) {
600
    // A missing file may be "provided" by an override buffer or file.
601
12
    if (OverriddenAbsPaths.count(F.getKey()))
602
0
      return false;
603
    // If a file previously recorded as missing exists as a regular file, then
604
    // consider the preamble out-of-date.
605
12
    if (auto Status = VFS->status(F.getKey())) {
606
0
      if (Status->isRegularFile())
607
0
        return false;
608
0
    }
609
12
  }
610
241
  return true;
611
241
}
612
613
void PrecompiledPreamble::AddImplicitPreamble(
614
    CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
615
330
    llvm::MemoryBuffer *MainFileBuffer) const {
616
330
  PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
617
330
  configurePreamble(Bounds, CI, VFS, MainFileBuffer);
618
330
}
619
620
void PrecompiledPreamble::OverridePreamble(
621
    CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
622
0
    llvm::MemoryBuffer *MainFileBuffer) const {
623
0
  auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), MainFileBuffer, 0);
624
0
  configurePreamble(Bounds, CI, VFS, MainFileBuffer);
625
0
}
626
627
PrecompiledPreamble::PrecompiledPreamble(
628
    PCHStorage Storage, std::vector<char> PreambleBytes,
629
    bool PreambleEndsAtStartOfLine,
630
    llvm::StringMap<PreambleFileHash> FilesInPreamble,
631
    llvm::StringSet<> MissingFiles)
632
    : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
633
      MissingFiles(std::move(MissingFiles)),
634
      PreambleBytes(std::move(PreambleBytes)),
635
89
      PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
636
89
  assert(this->Storage.getKind() != PCHStorage::Kind::Empty);
637
89
}
638
639
llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
640
89
PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile() {
641
  // FIXME: This is a hack so that we can override the preamble file during
642
  // crash-recovery testing, which is the only case where the preamble files
643
  // are not necessarily cleaned up.
644
89
  if (const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE"))
645
2
    return TempPCHFile(TmpFile);
646
647
87
  llvm::SmallString<64> File;
648
  // Using a version of createTemporaryFile with a file descriptor guarantees
649
  // that we would never get a race condition in a multi-threaded setting
650
  // (i.e., multiple threads getting the same temporary path).
651
87
  int FD;
652
87
  auto EC = llvm::sys::fs::createTemporaryFile("preamble", "pch", FD, File);
653
87
  if (EC)
654
0
    return EC;
655
  // We only needed to make sure the file exists, close the file right away.
656
87
  llvm::sys::Process::SafelyCloseFileDescriptor(FD);
657
87
  return TempPCHFile(std::string(std::move(File).str()));
658
87
}
659
660
PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath)
661
89
    : FilePath(std::move(FilePath)) {
662
89
  TemporaryFiles::getInstance().addFile(*this->FilePath);
663
89
}
664
665
712
PrecompiledPreamble::TempPCHFile::TempPCHFile(TempPCHFile &&Other) {
666
712
  FilePath = std::move(Other.FilePath);
667
712
  Other.FilePath = None;
668
712
}
669
670
PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::TempPCHFile::
671
0
operator=(TempPCHFile &&Other) {
672
0
  RemoveFileIfPresent();
673
674
0
  FilePath = std::move(Other.FilePath);
675
0
  Other.FilePath = None;
676
0
  return *this;
677
0
}
678
679
800
PrecompiledPreamble::TempPCHFile::~TempPCHFile() { RemoveFileIfPresent(); }
680
681
800
void PrecompiledPreamble::TempPCHFile::RemoveFileIfPresent() {
682
800
  if (FilePath) {
683
88
    TemporaryFiles::getInstance().removeFile(*FilePath);
684
88
    FilePath = None;
685
88
  }
686
800
}
687
688
749
llvm::StringRef PrecompiledPreamble::TempPCHFile::getFilePath() const {
689
749
  assert(FilePath && "TempPCHFile doesn't have a FilePath. Had it been moved?");
690
749
  return *FilePath;
691
749
}
692
693
PrecompiledPreamble::PCHStorage::PCHStorage(TempPCHFile File)
694
89
    : StorageKind(Kind::TempFile) {
695
89
  new (&asFile()) TempPCHFile(std::move(File));
696
89
}
697
698
PrecompiledPreamble::PCHStorage::PCHStorage(InMemoryPreamble Memory)
699
0
    : StorageKind(Kind::InMemory) {
700
0
  new (&asMemory()) InMemoryPreamble(std::move(Memory));
701
0
}
702
703
356
PrecompiledPreamble::PCHStorage::PCHStorage(PCHStorage &&Other) : PCHStorage() {
704
356
  *this = std::move(Other);
705
356
}
Unexecuted instantiation: clang::PrecompiledPreamble::PCHStorage::PCHStorage(clang::PrecompiledPreamble::PCHStorage&&)
clang::PrecompiledPreamble::PCHStorage::PCHStorage(clang::PrecompiledPreamble::PCHStorage&&)
Line
Count
Source
703
356
PrecompiledPreamble::PCHStorage::PCHStorage(PCHStorage &&Other) : PCHStorage() {
704
356
  *this = std::move(Other);
705
356
}
706
707
PrecompiledPreamble::PCHStorage &PrecompiledPreamble::PCHStorage::
708
356
operator=(PCHStorage &&Other) {
709
356
  destroy();
710
711
356
  StorageKind = Other.StorageKind;
712
356
  switch (StorageKind) {
713
0
  case Kind::Empty:
714
    // do nothing;
715
0
    break;
716
356
  case Kind::TempFile:
717
356
    new (&asFile()) TempPCHFile(std::move(Other.asFile()));
718
356
    break;
719
0
  case Kind::InMemory:
720
0
    new (&asMemory()) InMemoryPreamble(std::move(Other.asMemory()));
721
0
    break;
722
356
  }
723
724
356
  Other.setEmpty();
725
356
  return *this;
726
356
}
727
728
444
PrecompiledPreamble::PCHStorage::~PCHStorage() { destroy(); }
729
730
PrecompiledPreamble::PCHStorage::Kind
731
2.08k
PrecompiledPreamble::PCHStorage::getKind() const {
732
2.08k
  return StorageKind;
733
2.08k
}
734
735
1.66k
PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::PCHStorage::asFile() {
736
1.66k
  assert(getKind() == Kind::TempFile);
737
1.66k
  return *reinterpret_cast<TempPCHFile *>(Storage.buffer);
738
1.66k
}
739
740
const PrecompiledPreamble::TempPCHFile &
741
330
PrecompiledPreamble::PCHStorage::asFile() const {
742
330
  return const_cast<PCHStorage *>(this)->asFile();
743
330
}
744
745
PrecompiledPreamble::InMemoryPreamble &
746
0
PrecompiledPreamble::PCHStorage::asMemory() {
747
0
  assert(getKind() == Kind::InMemory);
748
0
  return *reinterpret_cast<InMemoryPreamble *>(Storage.buffer);
749
0
}
750
751
const PrecompiledPreamble::InMemoryPreamble &
752
0
PrecompiledPreamble::PCHStorage::asMemory() const {
753
0
  return const_cast<PCHStorage *>(this)->asMemory();
754
0
}
755
756
1.15k
void PrecompiledPreamble::PCHStorage::destroy() {
757
1.15k
  switch (StorageKind) {
758
712
  case Kind::Empty:
759
712
    return;
760
444
  case Kind::TempFile:
761
444
    asFile().~TempPCHFile();
762
444
    return;
763
0
  case Kind::InMemory:
764
0
    asMemory().~InMemoryPreamble();
765
0
    return;
766
1.15k
  }
767
1.15k
}
768
769
356
void PrecompiledPreamble::PCHStorage::setEmpty() {
770
356
  destroy();
771
356
  StorageKind = Kind::Empty;
772
356
}
773
774
PrecompiledPreamble::PreambleFileHash
775
PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
776
147
                                                     time_t ModTime) {
777
147
  PreambleFileHash Result;
778
147
  Result.Size = Size;
779
147
  Result.ModTime = ModTime;
780
147
  Result.MD5 = {};
781
147
  return Result;
782
147
}
783
784
PrecompiledPreamble::PreambleFileHash
785
PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
786
16
    const llvm::MemoryBuffer *Buffer) {
787
16
  PreambleFileHash Result;
788
16
  Result.Size = Buffer->getBufferSize();
789
16
  Result.ModTime = 0;
790
791
16
  llvm::MD5 MD5Ctx;
792
16
  MD5Ctx.update(Buffer->getBuffer().data());
793
16
  MD5Ctx.final(Result.MD5);
794
795
16
  return Result;
796
16
}
797
798
void PrecompiledPreamble::configurePreamble(
799
    PreambleBounds Bounds, CompilerInvocation &CI,
800
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
801
330
    llvm::MemoryBuffer *MainFileBuffer) const {
802
330
  assert(VFS);
803
804
330
  auto &PreprocessorOpts = CI.getPreprocessorOpts();
805
806
  // Remap main file to point to MainFileBuffer.
807
330
  auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
808
330
  PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
809
810
  // Configure ImpicitPCHInclude.
811
330
  PreprocessorOpts.PrecompiledPreambleBytes.first = Bounds.Size;
812
330
  PreprocessorOpts.PrecompiledPreambleBytes.second =
813
330
      Bounds.PreambleEndsAtStartOfLine;
814
330
  PreprocessorOpts.DisablePCHValidation = true;
815
816
330
  setupPreambleStorage(Storage, PreprocessorOpts, VFS);
817
330
}
818
819
void PrecompiledPreamble::setupPreambleStorage(
820
    const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
821
330
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS) {
822
330
  if (Storage.getKind() == PCHStorage::Kind::TempFile) {
823
330
    const TempPCHFile &PCHFile = Storage.asFile();
824
330
    PreprocessorOpts.ImplicitPCHInclude = std::string(PCHFile.getFilePath());
825
826
    // Make sure we can access the PCH file even if we're using a VFS
827
330
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> RealFS =
828
330
        llvm::vfs::getRealFileSystem();
829
330
    auto PCHPath = PCHFile.getFilePath();
830
330
    if (VFS == RealFS || 
VFS->exists(PCHPath)13
)
831
317
      return;
832
13
    auto Buf = RealFS->getBufferForFile(PCHPath);
833
13
    if (!Buf) {
834
      // We can't read the file even from RealFS, this is clearly an error,
835
      // but we'll just leave the current VFS as is and let clang's code
836
      // figure out what to do with missing PCH.
837
0
      return;
838
0
    }
839
840
    // We have a slight inconsistency here -- we're using the VFS to
841
    // read files, but the PCH was generated in the real file system.
842
13
    VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
843
0
  } else {
844
0
    assert(Storage.getKind() == PCHStorage::Kind::InMemory);
845
    // For in-memory preamble, we have to provide a VFS overlay that makes it
846
    // accessible.
847
0
    StringRef PCHPath = getInMemoryPreamblePath();
848
0
    PreprocessorOpts.ImplicitPCHInclude = std::string(PCHPath);
849
850
0
    auto Buf = llvm::MemoryBuffer::getMemBuffer(Storage.asMemory().Data);
851
0
    VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
852
0
  }
853
330
}
854
855
89
void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
856
89
void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
857
0
void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
858
0
void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
859
0
std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
860
0
  return nullptr;
861
0
}
862
89
CommentHandler *PreambleCallbacks::getCommentHandler() { return nullptr; }
863
864
static llvm::ManagedStatic<BuildPreambleErrorCategory> BuildPreambleErrCategory;
865
866
0
std::error_code clang::make_error_code(BuildPreambleError Error) {
867
0
  return std::error_code(static_cast<int>(Error), *BuildPreambleErrCategory);
868
0
}
869
870
0
const char *BuildPreambleErrorCategory::name() const noexcept {
871
0
  return "build-preamble.error";
872
0
}
873
874
0
std::string BuildPreambleErrorCategory::message(int condition) const {
875
0
  switch (static_cast<BuildPreambleError>(condition)) {
876
0
  case BuildPreambleError::CouldntCreateTempFile:
877
0
    return "Could not create temporary file for PCH";
878
0
  case BuildPreambleError::CouldntCreateTargetInfo:
879
0
    return "CreateTargetInfo() return null";
880
0
  case BuildPreambleError::BeginSourceFileFailed:
881
0
    return "BeginSourceFile() return an error";
882
0
  case BuildPreambleError::CouldntEmitPCH:
883
0
    return "Could not emit PCH";
884
0
  case BuildPreambleError::BadInputs:
885
0
    return "Command line arguments must contain exactly one source file";
886
0
  }
887
0
  llvm_unreachable("unexpected BuildPreambleError");
888
0
}