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/Mutex.h"
31 #include "llvm/Support/MutexGuard.h"
32 #include "llvm/Support/Process.h"
33 #include "llvm/Support/VirtualFileSystem.h"
34 #include <limits>
35 #include <utility>
36 
37 using namespace clang;
38 
39 namespace {
40 
41 StringRef getInMemoryPreamblePath() {
42 #if defined(LLVM_ON_UNIX)
43   return "/__clang_tmp/___clang_inmemory_preamble___";
44 #elif defined(_WIN32)
45   return "C:\\__clang_tmp\\___clang_inmemory_preamble___";
46 #else
47 #warning "Unknown platform. Defaulting to UNIX-style paths for in-memory PCHs"
48   return "/__clang_tmp/___clang_inmemory_preamble___";
49 #endif
50 }
51 
52 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
53 createVFSOverlayForPreamblePCH(StringRef PCHFilename,
54                                std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,
55                                IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
56   // We want only the PCH file from the real filesystem to be available,
57   // so we create an in-memory VFS with just that and overlay it on top.
58   IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> PCHFS(
59       new llvm::vfs::InMemoryFileSystem());
60   PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer));
61   IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> Overlay(
62       new llvm::vfs::OverlayFileSystem(VFS));
63   Overlay->pushOverlay(PCHFS);
64   return Overlay;
65 }
66 
67 class PreambleDependencyCollector : public DependencyCollector {
68 public:
69   // We want to collect all dependencies for correctness. Avoiding the real
70   // system dependencies (e.g. stl from /usr/lib) would probably be a good idea,
71   // but there is no way to distinguish between those and the ones that can be
72   // spuriously added by '-isystem' (e.g. to suppress warnings from those
73   // headers).
74   bool needSystemDependencies() override { return true; }
75 };
76 
77 /// Keeps a track of files to be deleted in destructor.
78 class TemporaryFiles {
79 public:
80   // A static instance to be used by all clients.
81   static TemporaryFiles &getInstance();
82 
83 private:
84   // Disallow constructing the class directly.
85   TemporaryFiles() = default;
86   // Disallow copy.
87   TemporaryFiles(const TemporaryFiles &) = delete;
88 
89 public:
90   ~TemporaryFiles();
91 
92   /// Adds \p File to a set of tracked files.
93   void addFile(StringRef File);
94 
95   /// Remove \p File from disk and from the set of tracked files.
96   void removeFile(StringRef File);
97 
98 private:
99   llvm::sys::SmartMutex<false> Mutex;
100   llvm::StringSet<> Files;
101 };
102 
103 TemporaryFiles &TemporaryFiles::getInstance() {
104   static TemporaryFiles Instance;
105   return Instance;
106 }
107 
108 TemporaryFiles::~TemporaryFiles() {
109   llvm::MutexGuard Guard(Mutex);
110   for (const auto &File : Files)
111     llvm::sys::fs::remove(File.getKey());
112 }
113 
114 void TemporaryFiles::addFile(StringRef File) {
115   llvm::MutexGuard Guard(Mutex);
116   auto IsInserted = Files.insert(File).second;
117   (void)IsInserted;
118   assert(IsInserted && "File has already been added");
119 }
120 
121 void TemporaryFiles::removeFile(StringRef File) {
122   llvm::MutexGuard Guard(Mutex);
123   auto WasPresent = Files.erase(File);
124   (void)WasPresent;
125   assert(WasPresent && "File was not tracked");
126   llvm::sys::fs::remove(File);
127 }
128 
129 class PrecompilePreambleAction : public ASTFrontendAction {
130 public:
131   PrecompilePreambleAction(std::string *InMemStorage,
132                            PreambleCallbacks &Callbacks)
133       : InMemStorage(InMemStorage), Callbacks(Callbacks) {}
134 
135   std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
136                                                  StringRef InFile) override;
137 
138   bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
139 
140   void setEmittedPreamblePCH(ASTWriter &Writer) {
141     this->HasEmittedPreamblePCH = true;
142     Callbacks.AfterPCHEmitted(Writer);
143   }
144 
145   bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
146   bool hasCodeCompletionSupport() const override { return false; }
147   bool hasASTFileSupport() const override { return false; }
148   TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
149 
150 private:
151   friend class PrecompilePreambleConsumer;
152 
153   bool HasEmittedPreamblePCH = false;
154   std::string *InMemStorage;
155   PreambleCallbacks &Callbacks;
156 };
157 
158 class PrecompilePreambleConsumer : public PCHGenerator {
159 public:
160   PrecompilePreambleConsumer(PrecompilePreambleAction &Action,
161                              const Preprocessor &PP,
162                              InMemoryModuleCache &ModuleCache,
163                              StringRef isysroot,
164                              std::unique_ptr<raw_ostream> Out)
165       : PCHGenerator(PP, ModuleCache, "", isysroot,
166                      std::make_shared<PCHBuffer>(),
167                      ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
168                      /*AllowASTWithErrors=*/true),
169         Action(Action), Out(std::move(Out)) {}
170 
171   bool HandleTopLevelDecl(DeclGroupRef DG) override {
172     Action.Callbacks.HandleTopLevelDecl(DG);
173     return true;
174   }
175 
176   void HandleTranslationUnit(ASTContext &Ctx) override {
177     PCHGenerator::HandleTranslationUnit(Ctx);
178     if (!hasEmittedPCH())
179       return;
180 
181     // Write the generated bitstream to "Out".
182     *Out << getPCH();
183     // Make sure it hits disk now.
184     Out->flush();
185     // Free the buffer.
186     llvm::SmallVector<char, 0> Empty;
187     getPCH() = std::move(Empty);
188 
189     Action.setEmittedPreamblePCH(getWriter());
190   }
191 
192 private:
193   PrecompilePreambleAction &Action;
194   std::unique_ptr<raw_ostream> Out;
195 };
196 
197 std::unique_ptr<ASTConsumer>
198 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
199                                             StringRef InFile) {
200   std::string Sysroot;
201   if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
202     return nullptr;
203 
204   std::unique_ptr<llvm::raw_ostream> OS;
205   if (InMemStorage) {
206     OS = llvm::make_unique<llvm::raw_string_ostream>(*InMemStorage);
207   } else {
208     std::string OutputFile;
209     OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
210   }
211   if (!OS)
212     return nullptr;
213 
214   if (!CI.getFrontendOpts().RelocatablePCH)
215     Sysroot.clear();
216 
217   return llvm::make_unique<PrecompilePreambleConsumer>(
218       *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, std::move(OS));
219 }
220 
221 template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
222   if (!Val)
223     return false;
224   Output = std::move(*Val);
225   return true;
226 }
227 
228 } // namespace
229 
230 PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
231                                             llvm::MemoryBuffer *Buffer,
232                                             unsigned MaxLines) {
233   return Lexer::ComputePreamble(Buffer->getBuffer(), LangOpts, MaxLines);
234 }
235 
236 llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
237     const CompilerInvocation &Invocation,
238     const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
239     DiagnosticsEngine &Diagnostics,
240     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
241     std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
242     PreambleCallbacks &Callbacks) {
243   assert(VFS && "VFS is null");
244 
245   auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
246   FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
247   PreprocessorOptions &PreprocessorOpts =
248       PreambleInvocation->getPreprocessorOpts();
249 
250   llvm::Optional<TempPCHFile> TempFile;
251   if (!StoreInMemory) {
252     // Create a temporary file for the precompiled preamble. In rare
253     // circumstances, this can fail.
254     llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> PreamblePCHFile =
255         PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile();
256     if (!PreamblePCHFile)
257       return BuildPreambleError::CouldntCreateTempFile;
258     TempFile = std::move(*PreamblePCHFile);
259   }
260 
261   PCHStorage Storage = StoreInMemory ? PCHStorage(InMemoryPreamble())
262                                      : PCHStorage(std::move(*TempFile));
263 
264   // Save the preamble text for later; we'll need to compare against it for
265   // subsequent reparses.
266   std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
267                                   MainFileBuffer->getBufferStart() +
268                                       Bounds.Size);
269   bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
270 
271   // Tell the compiler invocation to generate a temporary precompiled header.
272   FrontendOpts.ProgramAction = frontend::GeneratePCH;
273   FrontendOpts.OutputFile = 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   const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
540   if (TmpFile)
541     return TempPCHFile::createFromCustomPath(TmpFile);
542   return TempPCHFile::createInSystemTempDir("preamble", "pch");
543 }
544 
545 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
546 PrecompiledPreamble::TempPCHFile::createInSystemTempDir(const Twine &Prefix,
547                                                         StringRef Suffix) {
548   llvm::SmallString<64> File;
549   // Using a version of createTemporaryFile with a file descriptor guarantees
550   // that we would never get a race condition in a multi-threaded setting
551   // (i.e., multiple threads getting the same temporary path).
552   int FD;
553   auto EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, FD, File);
554   if (EC)
555     return EC;
556   // We only needed to make sure the file exists, close the file right away.
557   llvm::sys::Process::SafelyCloseFileDescriptor(FD);
558   return TempPCHFile(std::move(File).str());
559 }
560 
561 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
562 PrecompiledPreamble::TempPCHFile::createFromCustomPath(const Twine &Path) {
563   return TempPCHFile(Path.str());
564 }
565 
566 PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath)
567     : FilePath(std::move(FilePath)) {
568   TemporaryFiles::getInstance().addFile(*this->FilePath);
569 }
570 
571 PrecompiledPreamble::TempPCHFile::TempPCHFile(TempPCHFile &&Other) {
572   FilePath = std::move(Other.FilePath);
573   Other.FilePath = None;
574 }
575 
576 PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::TempPCHFile::
577 operator=(TempPCHFile &&Other) {
578   RemoveFileIfPresent();
579 
580   FilePath = std::move(Other.FilePath);
581   Other.FilePath = None;
582   return *this;
583 }
584 
585 PrecompiledPreamble::TempPCHFile::~TempPCHFile() { RemoveFileIfPresent(); }
586 
587 void PrecompiledPreamble::TempPCHFile::RemoveFileIfPresent() {
588   if (FilePath) {
589     TemporaryFiles::getInstance().removeFile(*FilePath);
590     FilePath = None;
591   }
592 }
593 
594 llvm::StringRef PrecompiledPreamble::TempPCHFile::getFilePath() const {
595   assert(FilePath && "TempPCHFile doesn't have a FilePath. Had it been moved?");
596   return *FilePath;
597 }
598 
599 PrecompiledPreamble::PCHStorage::PCHStorage(TempPCHFile File)
600     : StorageKind(Kind::TempFile) {
601   new (&asFile()) TempPCHFile(std::move(File));
602 }
603 
604 PrecompiledPreamble::PCHStorage::PCHStorage(InMemoryPreamble Memory)
605     : StorageKind(Kind::InMemory) {
606   new (&asMemory()) InMemoryPreamble(std::move(Memory));
607 }
608 
609 PrecompiledPreamble::PCHStorage::PCHStorage(PCHStorage &&Other) : PCHStorage() {
610   *this = std::move(Other);
611 }
612 
613 PrecompiledPreamble::PCHStorage &PrecompiledPreamble::PCHStorage::
614 operator=(PCHStorage &&Other) {
615   destroy();
616 
617   StorageKind = Other.StorageKind;
618   switch (StorageKind) {
619   case Kind::Empty:
620     // do nothing;
621     break;
622   case Kind::TempFile:
623     new (&asFile()) TempPCHFile(std::move(Other.asFile()));
624     break;
625   case Kind::InMemory:
626     new (&asMemory()) InMemoryPreamble(std::move(Other.asMemory()));
627     break;
628   }
629 
630   Other.setEmpty();
631   return *this;
632 }
633 
634 PrecompiledPreamble::PCHStorage::~PCHStorage() { destroy(); }
635 
636 PrecompiledPreamble::PCHStorage::Kind
637 PrecompiledPreamble::PCHStorage::getKind() const {
638   return StorageKind;
639 }
640 
641 PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::PCHStorage::asFile() {
642   assert(getKind() == Kind::TempFile);
643   return *reinterpret_cast<TempPCHFile *>(Storage.buffer);
644 }
645 
646 const PrecompiledPreamble::TempPCHFile &
647 PrecompiledPreamble::PCHStorage::asFile() const {
648   return const_cast<PCHStorage *>(this)->asFile();
649 }
650 
651 PrecompiledPreamble::InMemoryPreamble &
652 PrecompiledPreamble::PCHStorage::asMemory() {
653   assert(getKind() == Kind::InMemory);
654   return *reinterpret_cast<InMemoryPreamble *>(Storage.buffer);
655 }
656 
657 const PrecompiledPreamble::InMemoryPreamble &
658 PrecompiledPreamble::PCHStorage::asMemory() const {
659   return const_cast<PCHStorage *>(this)->asMemory();
660 }
661 
662 void PrecompiledPreamble::PCHStorage::destroy() {
663   switch (StorageKind) {
664   case Kind::Empty:
665     return;
666   case Kind::TempFile:
667     asFile().~TempPCHFile();
668     return;
669   case Kind::InMemory:
670     asMemory().~InMemoryPreamble();
671     return;
672   }
673 }
674 
675 void PrecompiledPreamble::PCHStorage::setEmpty() {
676   destroy();
677   StorageKind = Kind::Empty;
678 }
679 
680 PrecompiledPreamble::PreambleFileHash
681 PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
682                                                      time_t ModTime) {
683   PreambleFileHash Result;
684   Result.Size = Size;
685   Result.ModTime = ModTime;
686   Result.MD5 = {};
687   return Result;
688 }
689 
690 PrecompiledPreamble::PreambleFileHash
691 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
692     const llvm::MemoryBuffer *Buffer) {
693   PreambleFileHash Result;
694   Result.Size = Buffer->getBufferSize();
695   Result.ModTime = 0;
696 
697   llvm::MD5 MD5Ctx;
698   MD5Ctx.update(Buffer->getBuffer().data());
699   MD5Ctx.final(Result.MD5);
700 
701   return Result;
702 }
703 
704 void PrecompiledPreamble::configurePreamble(
705     PreambleBounds Bounds, CompilerInvocation &CI,
706     IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
707     llvm::MemoryBuffer *MainFileBuffer) const {
708   assert(VFS);
709 
710   auto &PreprocessorOpts = CI.getPreprocessorOpts();
711 
712   // Remap main file to point to MainFileBuffer.
713   auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
714   PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
715 
716   // Configure ImpicitPCHInclude.
717   PreprocessorOpts.PrecompiledPreambleBytes.first = Bounds.Size;
718   PreprocessorOpts.PrecompiledPreambleBytes.second =
719       Bounds.PreambleEndsAtStartOfLine;
720   PreprocessorOpts.DisablePCHValidation = true;
721 
722   setupPreambleStorage(Storage, PreprocessorOpts, VFS);
723 }
724 
725 void PrecompiledPreamble::setupPreambleStorage(
726     const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
727     IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS) {
728   if (Storage.getKind() == PCHStorage::Kind::TempFile) {
729     const TempPCHFile &PCHFile = Storage.asFile();
730     PreprocessorOpts.ImplicitPCHInclude = PCHFile.getFilePath();
731 
732     // Make sure we can access the PCH file even if we're using a VFS
733     IntrusiveRefCntPtr<llvm::vfs::FileSystem> RealFS =
734         llvm::vfs::getRealFileSystem();
735     auto PCHPath = PCHFile.getFilePath();
736     if (VFS == RealFS || VFS->exists(PCHPath))
737       return;
738     auto Buf = RealFS->getBufferForFile(PCHPath);
739     if (!Buf) {
740       // We can't read the file even from RealFS, this is clearly an error,
741       // but we'll just leave the current VFS as is and let clang's code
742       // figure out what to do with missing PCH.
743       return;
744     }
745 
746     // We have a slight inconsistency here -- we're using the VFS to
747     // read files, but the PCH was generated in the real file system.
748     VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
749   } else {
750     assert(Storage.getKind() == PCHStorage::Kind::InMemory);
751     // For in-memory preamble, we have to provide a VFS overlay that makes it
752     // accessible.
753     StringRef PCHPath = getInMemoryPreamblePath();
754     PreprocessorOpts.ImplicitPCHInclude = PCHPath;
755 
756     auto Buf = llvm::MemoryBuffer::getMemBuffer(Storage.asMemory().Data);
757     VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
758   }
759 }
760 
761 void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
762 void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
763 void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
764 void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
765 std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
766   return nullptr;
767 }
768 CommentHandler *PreambleCallbacks::getCommentHandler() { return nullptr; }
769 
770 static llvm::ManagedStatic<BuildPreambleErrorCategory> BuildPreambleErrCategory;
771 
772 std::error_code clang::make_error_code(BuildPreambleError Error) {
773   return std::error_code(static_cast<int>(Error), *BuildPreambleErrCategory);
774 }
775 
776 const char *BuildPreambleErrorCategory::name() const noexcept {
777   return "build-preamble.error";
778 }
779 
780 std::string BuildPreambleErrorCategory::message(int condition) const {
781   switch (static_cast<BuildPreambleError>(condition)) {
782   case BuildPreambleError::CouldntCreateTempFile:
783     return "Could not create temporary file for PCH";
784   case BuildPreambleError::CouldntCreateTargetInfo:
785     return "CreateTargetInfo() return null";
786   case BuildPreambleError::BeginSourceFileFailed:
787     return "BeginSourceFile() return an error";
788   case BuildPreambleError::CouldntEmitPCH:
789     return "Could not emit PCH";
790   case BuildPreambleError::BadInputs:
791     return "Command line arguments must contain exactly one source file";
792   }
793   llvm_unreachable("unexpected BuildPreambleError");
794 }
795