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