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