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