Coverage Report

Created: 2022-01-18 06:27

/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
294
  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
90
      : 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
96
                          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
96
    if (File != nullptr)
109
95
      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
83
  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
179
TemporaryFiles &TemporaryFiles::getInstance() {
170
179
  static TemporaryFiles Instance;
171
179
  return Instance;
172
179
}
173
174
83
TemporaryFiles::~TemporaryFiles() {
175
83
  std::lock_guard<std::mutex> Guard(Mutex);
176
83
  for (const auto &File : Files)
177
1
    llvm::sys::fs::remove(File.getKey());
178
83
}
179
180
90
void TemporaryFiles::addFile(StringRef File) {
181
90
  std::lock_guard<std::mutex> Guard(Mutex);
182
90
  auto IsInserted = Files.insert(File).second;
183
90
  (void)IsInserted;
184
90
  assert(IsInserted && "File has already been added");
185
90
}
186
187
89
void TemporaryFiles::removeFile(StringRef File) {
188
89
  std::lock_guard<std::mutex> Guard(Mutex);
189
89
  auto WasPresent = Files.erase(File);
190
89
  (void)WasPresent;
191
89
  assert(WasPresent && "File was not tracked");
192
0
  llvm::sys::fs::remove(File);
193
89
}
194
195
class PrecompilePreambleAction : public ASTFrontendAction {
196
public:
197
  PrecompilePreambleAction(std::string *InMemStorage,
198
                           PreambleCallbacks &Callbacks)
199
90
      : InMemStorage(InMemStorage), Callbacks(Callbacks) {}
200
201
  std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
202
                                                 StringRef InFile) override;
203
204
180
  bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
205
206
90
  void setEmittedPreamblePCH(ASTWriter &Writer) {
207
90
    this->HasEmittedPreamblePCH = true;
208
90
    Callbacks.AfterPCHEmitted(Writer);
209
90
  }
210
211
90
  bool BeginSourceFileAction(CompilerInstance &CI) override {
212
90
    assert(CI.getLangOpts().CompilingPCH);
213
0
    return ASTFrontendAction::BeginSourceFileAction(CI);
214
90
  }
215
216
90
  bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
217
90
  bool hasCodeCompletionSupport() const override { return false; }
218
0
  bool hasASTFileSupport() const override { return false; }
219
180
  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
90
        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
90
  void HandleTranslationUnit(ASTContext &Ctx) override {
248
90
    PCHGenerator::HandleTranslationUnit(Ctx);
249
90
    if (!hasEmittedPCH())
250
0
      return;
251
252
    // Write the generated bitstream to "Out".
253
90
    *Out << getPCH();
254
    // Make sure it hits disk now.
255
90
    Out->flush();
256
    // Free the buffer.
257
90
    llvm::SmallVector<char, 0> Empty;
258
90
    getPCH() = std::move(Empty);
259
260
90
    Action.setEmittedPreamblePCH(getWriter());
261
90
  }
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
90
                                            StringRef InFile) {
275
90
  std::string Sysroot;
276
90
  if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
277
0
    return nullptr;
278
279
90
  std::unique_ptr<llvm::raw_ostream> OS;
280
90
  if (InMemStorage) {
281
0
    OS = std::make_unique<llvm::raw_string_ostream>(*InMemStorage);
282
90
  } else {
283
90
    std::string OutputFile;
284
90
    OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
285
90
  }
286
90
  if (!OS)
287
0
    return nullptr;
288
289
90
  if (!CI.getFrontendOpts().RelocatablePCH)
290
90
    Sysroot.clear();
291
292
90
  return std::make_unique<PrecompilePreambleConsumer>(
293
90
      *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, std::move(OS));
294
90
}
295
296
466
template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
297
466
  if (!Val)
298
2
    return false;
299
464
  Output = std::move(*Val);
300
464
  return true;
301
466
}
302
303
} // namespace
304
305
PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
306
                                            const llvm::MemoryBufferRef &Buffer,
307
514
                                            unsigned MaxLines) {
308
514
  return Lexer::ComputePreamble(Buffer.getBuffer(), LangOpts, MaxLines);
309
514
}
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
90
    PreambleCallbacks &Callbacks) {
318
90
  assert(VFS && "VFS is null");
319
320
0
  auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
321
90
  FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
322
90
  PreprocessorOptions &PreprocessorOpts =
323
90
      PreambleInvocation->getPreprocessorOpts();
324
325
90
  llvm::Optional<TempPCHFile> TempFile;
326
90
  if (!StoreInMemory) {
327
    // Create a temporary file for the precompiled preamble. In rare
328
    // circumstances, this can fail.
329
90
    llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> PreamblePCHFile =
330
90
        PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile();
331
90
    if (!PreamblePCHFile)
332
0
      return BuildPreambleError::CouldntCreateTempFile;
333
90
    TempFile = std::move(*PreamblePCHFile);
334
90
  }
335
336
90
  PCHStorage Storage = StoreInMemory ? 
PCHStorage(InMemoryPreamble())0
337
90
                                     : PCHStorage(std::move(*TempFile));
338
339
  // Save the preamble text for later; we'll need to compare against it for
340
  // subsequent reparses.
341
90
  std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
342
90
                                  MainFileBuffer->getBufferStart() +
343
90
                                      Bounds.Size);
344
90
  bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
345
346
  // Tell the compiler invocation to generate a temporary precompiled header.
347
90
  FrontendOpts.ProgramAction = frontend::GeneratePCH;
348
90
  FrontendOpts.OutputFile =
349
90
      std::string(StoreInMemory ? 
getInMemoryPreamblePath()0
350
90
                                : Storage.asFile().getFilePath());
351
90
  PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
352
90
  PreprocessorOpts.PrecompiledPreambleBytes.second = false;
353
  // Inform preprocessor to record conditional stack when building the preamble.
354
90
  PreprocessorOpts.GeneratePreamble = true;
355
356
  // Create the compiler instance to use for building the precompiled preamble.
357
90
  std::unique_ptr<CompilerInstance> Clang(
358
90
      new CompilerInstance(std::move(PCHContainerOps)));
359
360
  // Recover resources if we crash before exiting this method.
361
90
  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
362
90
      Clang.get());
363
364
90
  Clang->setInvocation(std::move(PreambleInvocation));
365
90
  Clang->setDiagnostics(&Diagnostics);
366
367
  // Create the target instance.
368
90
  if (!Clang->createTarget())
369
0
    return BuildPreambleError::CouldntCreateTargetInfo;
370
371
90
  if (Clang->getFrontendOpts().Inputs.size() != 1 ||
372
90
      Clang->getFrontendOpts().Inputs[0].getKind().getFormat() !=
373
90
          InputKind::Source ||
374
90
      Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() ==
375
90
          Language::LLVM_IR) {
376
0
    return BuildPreambleError::BadInputs;
377
0
  }
378
379
  // Clear out old caches and data.
380
90
  Diagnostics.Reset();
381
90
  ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
382
383
90
  VFS =
384
90
      createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
385
386
  // Create a file manager object to provide access to and cache the filesystem.
387
90
  Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
388
389
  // Create the source manager.
390
90
  Clang->setSourceManager(
391
90
      new SourceManager(Diagnostics, Clang->getFileManager()));
392
393
90
  auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>();
394
90
  Clang->addDependencyCollector(PreambleDepCollector);
395
396
90
  Clang->getLangOpts().CompilingPCH = true;
397
398
  // Remap the main source file to the preamble buffer.
399
90
  StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
400
90
  auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
401
90
      MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
402
90
  if (PreprocessorOpts.RetainRemappedFileBuffers) {
403
    // MainFileBuffer will be deleted by unique_ptr after leaving the method.
404
90
    PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
405
90
  } else {
406
    // In that case, remapped buffer will be deleted by CompilerInstance on
407
    // BeginSourceFile, so we call release() to avoid double deletion.
408
0
    PreprocessorOpts.addRemappedFile(MainFilePath,
409
0
                                     PreambleInputBuffer.release());
410
0
  }
411
412
90
  std::unique_ptr<PrecompilePreambleAction> Act;
413
90
  Act.reset(new PrecompilePreambleAction(
414
90
      StoreInMemory ? 
&Storage.asMemory().Data0
: nullptr, Callbacks));
415
90
  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
416
0
    return BuildPreambleError::BeginSourceFileFailed;
417
418
  // Performed after BeginSourceFile to ensure Clang->Preprocessor can be
419
  // referenced in the callback.
420
90
  Callbacks.BeforeExecute(*Clang);
421
422
90
  std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
423
90
      Callbacks.createPPCallbacks();
424
90
  if (DelegatedPPCallbacks)
425
90
    Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
426
90
  if (auto CommentHandler = Callbacks.getCommentHandler())
427
0
    Clang->getPreprocessor().addCommentHandler(CommentHandler);
428
90
  llvm::StringSet<> MissingFiles;
429
90
  Clang->getPreprocessor().addPPCallbacks(
430
90
      std::make_unique<MissingFileCollector>(
431
90
          MissingFiles, Clang->getPreprocessor().getHeaderSearchInfo(),
432
90
          Clang->getSourceManager()));
433
434
90
  if (llvm::Error Err = Act->Execute())
435
0
    return errorToErrorCode(std::move(Err));
436
437
  // Run the callbacks.
438
90
  Callbacks.AfterExecute(*Clang);
439
440
90
  Act->EndSourceFile();
441
442
90
  if (!Act->hasEmittedPreamblePCH())
443
0
    return BuildPreambleError::CouldntEmitPCH;
444
445
  // Keep track of all of the files that the source manager knows about,
446
  // so we can verify whether they have changed or not.
447
90
  llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
448
449
90
  SourceManager &SourceMgr = Clang->getSourceManager();
450
249
  for (auto &Filename : PreambleDepCollector->getDependencies()) {
451
249
    auto FileOrErr = Clang->getFileManager().getFile(Filename);
452
249
    if (!FileOrErr ||
453
249
        
*FileOrErr == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())248
)
454
91
      continue;
455
158
    auto File = *FileOrErr;
456
158
    if (time_t ModTime = File->getModificationTime()) {
457
148
      FilesInPreamble[File->getName()] =
458
148
          PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
459
148
                                                               ModTime);
460
148
    } else {
461
10
      llvm::MemoryBufferRef Buffer =
462
10
          SourceMgr.getMemoryBufferForFileOrFake(File);
463
10
      FilesInPreamble[File->getName()] =
464
10
          PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
465
10
    }
466
158
  }
467
468
90
  return PrecompiledPreamble(
469
90
      std::move(Storage), std::move(PreambleBytes), PreambleEndsAtStartOfLine,
470
90
      std::move(FilesInPreamble), std::move(MissingFiles));
471
90
}
472
473
539
PreambleBounds PrecompiledPreamble::getBounds() const {
474
539
  return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
475
539
}
476
477
0
std::size_t PrecompiledPreamble::getSize() const {
478
0
  switch (Storage.getKind()) {
479
0
  case PCHStorage::Kind::Empty:
480
0
    assert(false && "Calling getSize() on invalid PrecompiledPreamble. "
481
0
                    "Was it std::moved?");
482
0
    return 0;
483
0
  case PCHStorage::Kind::InMemory:
484
0
    return Storage.asMemory().Data.size();
485
0
  case PCHStorage::Kind::TempFile: {
486
0
    uint64_t Result;
487
0
    if (llvm::sys::fs::file_size(Storage.asFile().getFilePath(), Result))
488
0
      return 0;
489
490
0
    assert(Result <= std::numeric_limits<std::size_t>::max() &&
491
0
           "file size did not fit into size_t");
492
0
    return Result;
493
0
  }
494
0
  }
495
0
  llvm_unreachable("Unhandled storage kind");
496
0
}
497
498
bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation,
499
                                   const llvm::MemoryBufferRef &MainFileBuffer,
500
                                   PreambleBounds Bounds,
501
253
                                   llvm::vfs::FileSystem &VFS) const {
502
503
253
  assert(
504
253
      Bounds.Size <= MainFileBuffer.getBufferSize() &&
505
253
      "Buffer is too large. Bounds were calculated from a different buffer?");
506
507
0
  auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
508
253
  PreprocessorOptions &PreprocessorOpts =
509
253
      PreambleInvocation->getPreprocessorOpts();
510
511
  // We've previously computed a preamble. Check whether we have the same
512
  // preamble now that we did before, and that there's enough space in
513
  // the main-file buffer within the precompiled preamble to fit the
514
  // new main file.
515
253
  if (PreambleBytes.size() != Bounds.Size ||
516
253
      
PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine247
||
517
253
      !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
518
247
                  MainFileBuffer.getBuffer().begin()))
519
6
    return false;
520
  // The preamble has not changed. We may be able to re-use the precompiled
521
  // preamble.
522
523
  // Check that none of the files used by the preamble have changed.
524
  // First, make a record of those files that have been overridden via
525
  // remapping or unsaved_files.
526
247
  std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
527
247
  llvm::StringSet<> OverriddenAbsPaths; // Either by buffers or files.
528
247
  for (const auto &R : PreprocessorOpts.RemappedFiles) {
529
0
    llvm::vfs::Status Status;
530
0
    if (!moveOnNoError(VFS.status(R.second), Status)) {
531
      // If we can't stat the file we're remapping to, assume that something
532
      // horrible happened.
533
0
      return false;
534
0
    }
535
    // If a mapped file was previously missing, then it has changed.
536
0
    llvm::SmallString<128> MappedPath(R.first);
537
0
    if (!VFS.makeAbsolute(MappedPath))
538
0
      OverriddenAbsPaths.insert(MappedPath);
539
540
0
    OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
541
0
        Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
542
0
  }
543
544
  // OverridenFileBuffers tracks only the files not found in VFS.
545
247
  llvm::StringMap<PreambleFileHash> OverridenFileBuffers;
546
247
  for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
547
6
    const PrecompiledPreamble::PreambleFileHash PreambleHash =
548
6
        PreambleFileHash::createForMemoryBuffer(RB.second->getMemBufferRef());
549
6
    llvm::vfs::Status Status;
550
6
    if (moveOnNoError(VFS.status(RB.first), Status))
551
4
      OverriddenFiles[Status.getUniqueID()] = PreambleHash;
552
2
    else
553
2
      OverridenFileBuffers[RB.first] = PreambleHash;
554
555
6
    llvm::SmallString<128> MappedPath(RB.first);
556
6
    if (!VFS.makeAbsolute(MappedPath))
557
6
      OverriddenAbsPaths.insert(MappedPath);
558
6
  }
559
560
  // Check whether anything has changed.
561
462
  for (const auto &F : FilesInPreamble) {
562
462
    auto OverridenFileBuffer = OverridenFileBuffers.find(F.first());
563
462
    if (OverridenFileBuffer != OverridenFileBuffers.end()) {
564
      // The file's buffer was remapped and the file was not found in VFS.
565
      // Check whether it matches up with the previous mapping.
566
2
      if (OverridenFileBuffer->second != F.second)
567
0
        return false;
568
2
      continue;
569
2
    }
570
571
460
    llvm::vfs::Status Status;
572
460
    if (!moveOnNoError(VFS.status(F.first()), Status)) {
573
      // If the file's buffer is not remapped and we can't stat it,
574
      // assume that something horrible happened.
575
0
      return false;
576
0
    }
577
578
460
    std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
579
460
        OverriddenFiles.find(Status.getUniqueID());
580
460
    if (Overridden != OverriddenFiles.end()) {
581
      // This file was remapped; check whether the newly-mapped file
582
      // matches up with the previous mapping.
583
4
      if (Overridden->second != F.second)
584
2
        return false;
585
2
      continue;
586
4
    }
587
588
    // Neither the file's buffer nor the file itself was remapped;
589
    // check whether it has changed on disk.
590
456
    if (Status.getSize() != uint64_t(F.second.Size) ||
591
456
        llvm::sys::toTimeT(Status.getLastModificationTime()) !=
592
454
            F.second.ModTime)
593
2
      return false;
594
456
  }
595
243
  for (const auto &F : MissingFiles) {
596
    // A missing file may be "provided" by an override buffer or file.
597
12
    if (OverriddenAbsPaths.count(F.getKey()))
598
0
      return false;
599
    // If a file previously recorded as missing exists as a regular file, then
600
    // consider the preamble out-of-date.
601
12
    if (auto Status = VFS.status(F.getKey())) {
602
0
      if (Status->isRegularFile())
603
0
        return false;
604
0
    }
605
12
  }
606
243
  return true;
607
243
}
608
609
void PrecompiledPreamble::AddImplicitPreamble(
610
    CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
611
333
    llvm::MemoryBuffer *MainFileBuffer) const {
612
333
  PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
613
333
  configurePreamble(Bounds, CI, VFS, MainFileBuffer);
614
333
}
615
616
void PrecompiledPreamble::OverridePreamble(
617
    CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
618
0
    llvm::MemoryBuffer *MainFileBuffer) const {
619
0
  auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), *MainFileBuffer, 0);
620
0
  configurePreamble(Bounds, CI, VFS, MainFileBuffer);
621
0
}
622
623
PrecompiledPreamble::PrecompiledPreamble(
624
    PCHStorage Storage, std::vector<char> PreambleBytes,
625
    bool PreambleEndsAtStartOfLine,
626
    llvm::StringMap<PreambleFileHash> FilesInPreamble,
627
    llvm::StringSet<> MissingFiles)
628
    : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
629
      MissingFiles(std::move(MissingFiles)),
630
      PreambleBytes(std::move(PreambleBytes)),
631
90
      PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
632
90
  assert(this->Storage.getKind() != PCHStorage::Kind::Empty);
633
90
}
634
635
llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
636
90
PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile() {
637
  // FIXME: This is a hack so that we can override the preamble file during
638
  // crash-recovery testing, which is the only case where the preamble files
639
  // are not necessarily cleaned up.
640
90
  if (const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE"))
641
2
    return TempPCHFile(TmpFile);
642
643
88
  llvm::SmallString<64> File;
644
  // Using a version of createTemporaryFile with a file descriptor guarantees
645
  // that we would never get a race condition in a multi-threaded setting
646
  // (i.e., multiple threads getting the same temporary path).
647
88
  int FD;
648
88
  auto EC = llvm::sys::fs::createTemporaryFile("preamble", "pch", FD, File);
649
88
  if (EC)
650
0
    return EC;
651
  // We only needed to make sure the file exists, close the file right away.
652
88
  llvm::sys::Process::SafelyCloseFileDescriptor(FD);
653
88
  return TempPCHFile(std::string(std::move(File).str()));
654
88
}
655
656
PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath)
657
90
    : FilePath(std::move(FilePath)) {
658
90
  TemporaryFiles::getInstance().addFile(*this->FilePath);
659
90
}
660
661
720
PrecompiledPreamble::TempPCHFile::TempPCHFile(TempPCHFile &&Other) {
662
720
  FilePath = std::move(Other.FilePath);
663
720
  Other.FilePath = None;
664
720
}
665
666
PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::TempPCHFile::
667
0
operator=(TempPCHFile &&Other) {
668
0
  RemoveFileIfPresent();
669
670
0
  FilePath = std::move(Other.FilePath);
671
0
  Other.FilePath = None;
672
0
  return *this;
673
0
}
674
675
809
PrecompiledPreamble::TempPCHFile::~TempPCHFile() { RemoveFileIfPresent(); }
676
677
809
void PrecompiledPreamble::TempPCHFile::RemoveFileIfPresent() {
678
809
  if (FilePath) {
679
89
    TemporaryFiles::getInstance().removeFile(*FilePath);
680
89
    FilePath = None;
681
89
  }
682
809
}
683
684
756
llvm::StringRef PrecompiledPreamble::TempPCHFile::getFilePath() const {
685
756
  assert(FilePath && "TempPCHFile doesn't have a FilePath. Had it been moved?");
686
0
  return *FilePath;
687
756
}
688
689
PrecompiledPreamble::PCHStorage::PCHStorage(TempPCHFile File)
690
90
    : StorageKind(Kind::TempFile) {
691
90
  new (&asFile()) TempPCHFile(std::move(File));
692
90
}
693
694
PrecompiledPreamble::PCHStorage::PCHStorage(InMemoryPreamble Memory)
695
0
    : StorageKind(Kind::InMemory) {
696
0
  new (&asMemory()) InMemoryPreamble(std::move(Memory));
697
0
}
698
699
360
PrecompiledPreamble::PCHStorage::PCHStorage(PCHStorage &&Other) : PCHStorage() {
700
360
  *this = std::move(Other);
701
360
}
Unexecuted instantiation: clang::PrecompiledPreamble::PCHStorage::PCHStorage(clang::PrecompiledPreamble::PCHStorage&&)
clang::PrecompiledPreamble::PCHStorage::PCHStorage(clang::PrecompiledPreamble::PCHStorage&&)
Line
Count
Source
699
360
PrecompiledPreamble::PCHStorage::PCHStorage(PCHStorage &&Other) : PCHStorage() {
700
360
  *this = std::move(Other);
701
360
}
702
703
PrecompiledPreamble::PCHStorage &PrecompiledPreamble::PCHStorage::
704
360
operator=(PCHStorage &&Other) {
705
360
  destroy();
706
707
360
  StorageKind = Other.StorageKind;
708
360
  switch (StorageKind) {
709
0
  case Kind::Empty:
710
    // do nothing;
711
0
    break;
712
360
  case Kind::TempFile:
713
360
    new (&asFile()) TempPCHFile(std::move(Other.asFile()));
714
360
    break;
715
0
  case Kind::InMemory:
716
0
    new (&asMemory()) InMemoryPreamble(std::move(Other.asMemory()));
717
0
    break;
718
360
  }
719
720
360
  Other.setEmpty();
721
360
  return *this;
722
360
}
723
724
449
PrecompiledPreamble::PCHStorage::~PCHStorage() { destroy(); }
725
726
PrecompiledPreamble::PCHStorage::Kind
727
2.10k
PrecompiledPreamble::PCHStorage::getKind() const {
728
2.10k
  return StorageKind;
729
2.10k
}
730
731
1.68k
PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::PCHStorage::asFile() {
732
1.68k
  assert(getKind() == Kind::TempFile);
733
0
  return *reinterpret_cast<TempPCHFile *>(&Storage);
734
1.68k
}
735
736
const PrecompiledPreamble::TempPCHFile &
737
333
PrecompiledPreamble::PCHStorage::asFile() const {
738
333
  return const_cast<PCHStorage *>(this)->asFile();
739
333
}
740
741
PrecompiledPreamble::InMemoryPreamble &
742
0
PrecompiledPreamble::PCHStorage::asMemory() {
743
0
  assert(getKind() == Kind::InMemory);
744
0
  return *reinterpret_cast<InMemoryPreamble *>(&Storage);
745
0
}
746
747
const PrecompiledPreamble::InMemoryPreamble &
748
0
PrecompiledPreamble::PCHStorage::asMemory() const {
749
0
  return const_cast<PCHStorage *>(this)->asMemory();
750
0
}
751
752
1.16k
void PrecompiledPreamble::PCHStorage::destroy() {
753
1.16k
  switch (StorageKind) {
754
720
  case Kind::Empty:
755
720
    return;
756
449
  case Kind::TempFile:
757
449
    asFile().~TempPCHFile();
758
449
    return;
759
0
  case Kind::InMemory:
760
0
    asMemory().~InMemoryPreamble();
761
0
    return;
762
1.16k
  }
763
1.16k
}
764
765
360
void PrecompiledPreamble::PCHStorage::setEmpty() {
766
360
  destroy();
767
360
  StorageKind = Kind::Empty;
768
360
}
769
770
PrecompiledPreamble::PreambleFileHash
771
PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
772
148
                                                     time_t ModTime) {
773
148
  PreambleFileHash Result;
774
148
  Result.Size = Size;
775
148
  Result.ModTime = ModTime;
776
148
  Result.MD5 = {};
777
148
  return Result;
778
148
}
779
780
PrecompiledPreamble::PreambleFileHash
781
PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
782
16
    const llvm::MemoryBufferRef &Buffer) {
783
16
  PreambleFileHash Result;
784
16
  Result.Size = Buffer.getBufferSize();
785
16
  Result.ModTime = 0;
786
787
16
  llvm::MD5 MD5Ctx;
788
16
  MD5Ctx.update(Buffer.getBuffer().data());
789
16
  MD5Ctx.final(Result.MD5);
790
791
16
  return Result;
792
16
}
793
794
void PrecompiledPreamble::configurePreamble(
795
    PreambleBounds Bounds, CompilerInvocation &CI,
796
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
797
333
    llvm::MemoryBuffer *MainFileBuffer) const {
798
333
  assert(VFS);
799
800
0
  auto &PreprocessorOpts = CI.getPreprocessorOpts();
801
802
  // Remap main file to point to MainFileBuffer.
803
333
  auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
804
333
  PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
805
806
  // Configure ImpicitPCHInclude.
807
333
  PreprocessorOpts.PrecompiledPreambleBytes.first = Bounds.Size;
808
333
  PreprocessorOpts.PrecompiledPreambleBytes.second =
809
333
      Bounds.PreambleEndsAtStartOfLine;
810
333
  PreprocessorOpts.DisablePCHOrModuleValidation =
811
333
      DisableValidationForModuleKind::PCH;
812
813
333
  setupPreambleStorage(Storage, PreprocessorOpts, VFS);
814
333
}
815
816
void PrecompiledPreamble::setupPreambleStorage(
817
    const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
818
333
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS) {
819
333
  if (Storage.getKind() == PCHStorage::Kind::TempFile) {
820
333
    const TempPCHFile &PCHFile = Storage.asFile();
821
333
    PreprocessorOpts.ImplicitPCHInclude = std::string(PCHFile.getFilePath());
822
823
    // Make sure we can access the PCH file even if we're using a VFS
824
333
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> RealFS =
825
333
        llvm::vfs::getRealFileSystem();
826
333
    auto PCHPath = PCHFile.getFilePath();
827
333
    if (VFS == RealFS || 
VFS->exists(PCHPath)13
)
828
320
      return;
829
13
    auto Buf = RealFS->getBufferForFile(PCHPath);
830
13
    if (!Buf) {
831
      // We can't read the file even from RealFS, this is clearly an error,
832
      // but we'll just leave the current VFS as is and let clang's code
833
      // figure out what to do with missing PCH.
834
0
      return;
835
0
    }
836
837
    // We have a slight inconsistency here -- we're using the VFS to
838
    // read files, but the PCH was generated in the real file system.
839
13
    VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
840
13
  } else {
841
0
    assert(Storage.getKind() == PCHStorage::Kind::InMemory);
842
    // For in-memory preamble, we have to provide a VFS overlay that makes it
843
    // accessible.
844
0
    StringRef PCHPath = getInMemoryPreamblePath();
845
0
    PreprocessorOpts.ImplicitPCHInclude = std::string(PCHPath);
846
847
0
    auto Buf = llvm::MemoryBuffer::getMemBuffer(Storage.asMemory().Data);
848
0
    VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
849
0
  }
850
333
}
851
852
90
void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
853
90
void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
854
0
void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
855
0
void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
856
0
std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
857
0
  return nullptr;
858
0
}
859
90
CommentHandler *PreambleCallbacks::getCommentHandler() { return nullptr; }
860
861
static llvm::ManagedStatic<BuildPreambleErrorCategory> BuildPreambleErrCategory;
862
863
0
std::error_code clang::make_error_code(BuildPreambleError Error) {
864
0
  return std::error_code(static_cast<int>(Error), *BuildPreambleErrCategory);
865
0
}
866
867
0
const char *BuildPreambleErrorCategory::name() const noexcept {
868
0
  return "build-preamble.error";
869
0
}
870
871
0
std::string BuildPreambleErrorCategory::message(int condition) const {
872
0
  switch (static_cast<BuildPreambleError>(condition)) {
873
0
  case BuildPreambleError::CouldntCreateTempFile:
874
0
    return "Could not create temporary file for PCH";
875
0
  case BuildPreambleError::CouldntCreateTargetInfo:
876
0
    return "CreateTargetInfo() return null";
877
0
  case BuildPreambleError::BeginSourceFileFailed:
878
0
    return "BeginSourceFile() return an error";
879
0
  case BuildPreambleError::CouldntEmitPCH:
880
0
    return "Could not emit PCH";
881
0
  case BuildPreambleError::BadInputs:
882
0
    return "Command line arguments must contain exactly one source file";
883
0
  }
884
0
  llvm_unreachable("unexpected BuildPreambleError");
885
0
}