blob: 5d6cc840a8eca8e0ca9b984afe9b159995056fb3 [file] [log] [blame]
Ilya Biryukov200b3282017-06-21 10:24:58 +00001//===--- PrecompiledPreamble.cpp - Build precompiled preambles --*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Ilya Biryukov200b3282017-06-21 10:24:58 +00006//
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/TargetInfo.h"
Ilya Biryukov200b3282017-06-21 10:24:58 +000016#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/Lexer.h"
Kadir Cetinkaya9e012e82019-02-04 09:42:33 +000021#include "clang/Lex/Preprocessor.h"
Ilya Biryukov200b3282017-06-21 10:24:58 +000022#include "clang/Lex/PreprocessorOptions.h"
23#include "clang/Serialization/ASTWriter.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/StringSet.h"
Ilya Biryukovdd9ea752017-11-17 10:09:02 +000026#include "llvm/Config/llvm-config.h"
Ilya Biryukov200b3282017-06-21 10:24:58 +000027#include "llvm/Support/CrashRecoveryContext.h"
28#include "llvm/Support/FileSystem.h"
29#include "llvm/Support/Mutex.h"
30#include "llvm/Support/MutexGuard.h"
Ilya Biryukovb88de412017-08-10 16:10:40 +000031#include "llvm/Support/Process.h"
Jonas Devliegherefc514902018-10-10 13:27:25 +000032#include "llvm/Support/VirtualFileSystem.h"
Ilya Biryukov923e3382017-12-21 14:04:39 +000033#include <limits>
Ilya Biryukov417085a2017-11-16 16:25:01 +000034#include <utility>
35
Ilya Biryukov200b3282017-06-21 10:24:58 +000036using namespace clang;
37
38namespace {
39
Ilya Biryukov417085a2017-11-16 16:25:01 +000040StringRef getInMemoryPreamblePath() {
41#if defined(LLVM_ON_UNIX)
42 return "/__clang_tmp/___clang_inmemory_preamble___";
Nico Weber1865df42018-04-27 19:11:14 +000043#elif defined(_WIN32)
Ilya Biryukov417085a2017-11-16 16:25:01 +000044 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
Jonas Devliegherefc514902018-10-10 13:27:25 +000051IntrusiveRefCntPtr<llvm::vfs::FileSystem>
Ilya Biryukov417085a2017-11-16 16:25:01 +000052createVFSOverlayForPreamblePCH(StringRef PCHFilename,
53 std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,
Jonas Devliegherefc514902018-10-10 13:27:25 +000054 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
Ilya Biryukov417085a2017-11-16 16:25:01 +000055 // 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.
Jonas Devliegherefc514902018-10-10 13:27:25 +000057 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> PCHFS(
58 new llvm::vfs::InMemoryFileSystem());
Ilya Biryukov417085a2017-11-16 16:25:01 +000059 PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer));
Jonas Devliegherefc514902018-10-10 13:27:25 +000060 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> Overlay(
61 new llvm::vfs::OverlayFileSystem(VFS));
Ilya Biryukov417085a2017-11-16 16:25:01 +000062 Overlay->pushOverlay(PCHFS);
63 return Overlay;
64}
65
Ilya Biryukove5801b02018-07-09 09:07:01 +000066class PreambleDependencyCollector : public DependencyCollector {
67public:
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
Ilya Biryukov200b3282017-06-21 10:24:58 +000076/// Keeps a track of files to be deleted in destructor.
77class TemporaryFiles {
78public:
79 // A static instance to be used by all clients.
80 static TemporaryFiles &getInstance();
81
82private:
83 // Disallow constructing the class directly.
84 TemporaryFiles() = default;
85 // Disallow copy.
86 TemporaryFiles(const TemporaryFiles &) = delete;
87
88public:
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
97private:
98 llvm::sys::SmartMutex<false> Mutex;
99 llvm::StringSet<> Files;
100};
101
102TemporaryFiles &TemporaryFiles::getInstance() {
103 static TemporaryFiles Instance;
104 return Instance;
105}
106
107TemporaryFiles::~TemporaryFiles() {
108 llvm::MutexGuard Guard(Mutex);
109 for (const auto &File : Files)
110 llvm::sys::fs::remove(File.getKey());
111}
112
113void TemporaryFiles::addFile(StringRef File) {
114 llvm::MutexGuard Guard(Mutex);
115 auto IsInserted = Files.insert(File).second;
Haojian Wu53dd6442017-06-21 11:26:58 +0000116 (void)IsInserted;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000117 assert(IsInserted && "File has already been added");
118}
119
120void TemporaryFiles::removeFile(StringRef File) {
121 llvm::MutexGuard Guard(Mutex);
122 auto WasPresent = Files.erase(File);
Haojian Wu53dd6442017-06-21 11:26:58 +0000123 (void)WasPresent;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000124 assert(WasPresent && "File was not tracked");
125 llvm::sys::fs::remove(File);
126}
127
Ilya Biryukov200b3282017-06-21 10:24:58 +0000128class PrecompilePreambleAction : public ASTFrontendAction {
129public:
Ilya Biryukov417085a2017-11-16 16:25:01 +0000130 PrecompilePreambleAction(std::string *InMemStorage,
131 PreambleCallbacks &Callbacks)
132 : InMemStorage(InMemStorage), Callbacks(Callbacks) {}
Ilya Biryukov200b3282017-06-21 10:24:58 +0000133
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
149private:
150 friend class PrecompilePreambleConsumer;
151
152 bool HasEmittedPreamblePCH = false;
Ilya Biryukov417085a2017-11-16 16:25:01 +0000153 std::string *InMemStorage;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000154 PreambleCallbacks &Callbacks;
155};
156
157class PrecompilePreambleConsumer : public PCHGenerator {
158public:
159 PrecompilePreambleConsumer(PrecompilePreambleAction &Action,
160 const Preprocessor &PP, StringRef isysroot,
161 std::unique_ptr<raw_ostream> Out)
162 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(),
163 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
164 /*AllowASTWithErrors=*/true),
165 Action(Action), Out(std::move(Out)) {}
166
167 bool HandleTopLevelDecl(DeclGroupRef DG) override {
168 Action.Callbacks.HandleTopLevelDecl(DG);
169 return true;
170 }
171
172 void HandleTranslationUnit(ASTContext &Ctx) override {
173 PCHGenerator::HandleTranslationUnit(Ctx);
174 if (!hasEmittedPCH())
175 return;
176
177 // Write the generated bitstream to "Out".
178 *Out << getPCH();
179 // Make sure it hits disk now.
180 Out->flush();
181 // Free the buffer.
182 llvm::SmallVector<char, 0> Empty;
183 getPCH() = std::move(Empty);
184
185 Action.setEmittedPreamblePCH(getWriter());
186 }
187
188private:
189 PrecompilePreambleAction &Action;
190 std::unique_ptr<raw_ostream> Out;
191};
192
193std::unique_ptr<ASTConsumer>
194PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000195 StringRef InFile) {
196 std::string Sysroot;
Ilya Biryukov417085a2017-11-16 16:25:01 +0000197 if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
198 return nullptr;
199
200 std::unique_ptr<llvm::raw_ostream> OS;
201 if (InMemStorage) {
202 OS = llvm::make_unique<llvm::raw_string_ostream>(*InMemStorage);
203 } else {
204 std::string OutputFile;
205 OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
206 }
Ilya Biryukov200b3282017-06-21 10:24:58 +0000207 if (!OS)
208 return nullptr;
209
210 if (!CI.getFrontendOpts().RelocatablePCH)
211 Sysroot.clear();
212
Ilya Biryukov200b3282017-06-21 10:24:58 +0000213 return llvm::make_unique<PrecompilePreambleConsumer>(
214 *this, CI.getPreprocessor(), Sysroot, std::move(OS));
215}
216
217template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
218 if (!Val)
219 return false;
220 Output = std::move(*Val);
221 return true;
222}
223
224} // namespace
225
226PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
227 llvm::MemoryBuffer *Buffer,
228 unsigned MaxLines) {
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000229 return Lexer::ComputePreamble(Buffer->getBuffer(), LangOpts, MaxLines);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000230}
231
232llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
233 const CompilerInvocation &Invocation,
234 const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000235 DiagnosticsEngine &Diagnostics,
236 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
Ilya Biryukov417085a2017-11-16 16:25:01 +0000237 std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000238 PreambleCallbacks &Callbacks) {
239 assert(VFS && "VFS is null");
240
Ilya Biryukov200b3282017-06-21 10:24:58 +0000241 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
242 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
243 PreprocessorOptions &PreprocessorOpts =
244 PreambleInvocation->getPreprocessorOpts();
245
Ilya Biryukov417085a2017-11-16 16:25:01 +0000246 llvm::Optional<TempPCHFile> TempFile;
247 if (!StoreInMemory) {
248 // Create a temporary file for the precompiled preamble. In rare
249 // circumstances, this can fail.
250 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> PreamblePCHFile =
251 PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile();
252 if (!PreamblePCHFile)
253 return BuildPreambleError::CouldntCreateTempFile;
254 TempFile = std::move(*PreamblePCHFile);
255 }
256
257 PCHStorage Storage = StoreInMemory ? PCHStorage(InMemoryPreamble())
258 : PCHStorage(std::move(*TempFile));
Ilya Biryukov200b3282017-06-21 10:24:58 +0000259
260 // Save the preamble text for later; we'll need to compare against it for
261 // subsequent reparses.
262 std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
263 MainFileBuffer->getBufferStart() +
264 Bounds.Size);
265 bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
266
267 // Tell the compiler invocation to generate a temporary precompiled header.
268 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Ilya Biryukov417085a2017-11-16 16:25:01 +0000269 FrontendOpts.OutputFile = StoreInMemory ? getInMemoryPreamblePath()
270 : Storage.asFile().getFilePath();
Ilya Biryukov200b3282017-06-21 10:24:58 +0000271 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
272 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Ilya Biryukoveb1ec872017-10-09 16:52:12 +0000273 // Inform preprocessor to record conditional stack when building the preamble.
274 PreprocessorOpts.GeneratePreamble = true;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000275
276 // Create the compiler instance to use for building the precompiled preamble.
277 std::unique_ptr<CompilerInstance> Clang(
278 new CompilerInstance(std::move(PCHContainerOps)));
279
280 // Recover resources if we crash before exiting this method.
281 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
282 Clang.get());
283
284 Clang->setInvocation(std::move(PreambleInvocation));
285 Clang->setDiagnostics(&Diagnostics);
286
287 // Create the target instance.
288 Clang->setTarget(TargetInfo::CreateTargetInfo(
289 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
290 if (!Clang->hasTarget())
291 return BuildPreambleError::CouldntCreateTargetInfo;
292
293 // Inform the target of the language options.
294 //
295 // FIXME: We shouldn't need to do this, the target should be immutable once
296 // created. This complexity should be lifted elsewhere.
297 Clang->getTarget().adjust(Clang->getLangOpts());
298
299 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
300 "Invocation must have exactly one source file!");
301 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
302 InputKind::Source &&
303 "FIXME: AST inputs not yet supported here!");
304 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
305 InputKind::LLVM_IR &&
306 "IR inputs not support here!");
307
308 // Clear out old caches and data.
309 Diagnostics.Reset();
310 ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
311
312 VFS =
313 createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000314
315 // Create a file manager object to provide access to and cache the filesystem.
316 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
317
318 // Create the source manager.
319 Clang->setSourceManager(
320 new SourceManager(Diagnostics, Clang->getFileManager()));
321
Ilya Biryukove5801b02018-07-09 09:07:01 +0000322 auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>();
Ilya Biryukov200b3282017-06-21 10:24:58 +0000323 Clang->addDependencyCollector(PreambleDepCollector);
324
325 // Remap the main source file to the preamble buffer.
326 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
327 auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
328 MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
329 if (PreprocessorOpts.RetainRemappedFileBuffers) {
330 // MainFileBuffer will be deleted by unique_ptr after leaving the method.
331 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
332 } else {
333 // In that case, remapped buffer will be deleted by CompilerInstance on
334 // BeginSourceFile, so we call release() to avoid double deletion.
335 PreprocessorOpts.addRemappedFile(MainFilePath,
336 PreambleInputBuffer.release());
337 }
338
339 std::unique_ptr<PrecompilePreambleAction> Act;
Ilya Biryukov417085a2017-11-16 16:25:01 +0000340 Act.reset(new PrecompilePreambleAction(
341 StoreInMemory ? &Storage.asMemory().Data : nullptr, Callbacks));
Ilya Biryukov1f8647d2017-12-20 16:48:56 +0000342 Callbacks.BeforeExecute(*Clang);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000343 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
344 return BuildPreambleError::BeginSourceFileFailed;
345
Ilya Biryukov41e90bc2017-12-15 11:27:51 +0000346 std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
347 Callbacks.createPPCallbacks();
348 if (DelegatedPPCallbacks)
349 Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
Kadir Cetinkaya9e012e82019-02-04 09:42:33 +0000350 if (auto CommentHandler = Callbacks.getCommentHandler())
351 Clang->getPreprocessor().addCommentHandler(CommentHandler);
Ilya Biryukov41e90bc2017-12-15 11:27:51 +0000352
Ilya Biryukov200b3282017-06-21 10:24:58 +0000353 Act->Execute();
354
355 // Run the callbacks.
356 Callbacks.AfterExecute(*Clang);
357
358 Act->EndSourceFile();
359
360 if (!Act->hasEmittedPreamblePCH())
361 return BuildPreambleError::CouldntEmitPCH;
362
363 // Keep track of all of the files that the source manager knows about,
364 // so we can verify whether they have changed or not.
365 llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
366
367 SourceManager &SourceMgr = Clang->getSourceManager();
368 for (auto &Filename : PreambleDepCollector->getDependencies()) {
369 const FileEntry *File = Clang->getFileManager().getFile(Filename);
370 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
371 continue;
372 if (time_t ModTime = File->getModificationTime()) {
373 FilesInPreamble[File->getName()] =
374 PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
375 ModTime);
376 } else {
377 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
378 FilesInPreamble[File->getName()] =
379 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
380 }
381 }
382
Ilya Biryukov417085a2017-11-16 16:25:01 +0000383 return PrecompiledPreamble(std::move(Storage), std::move(PreambleBytes),
384 PreambleEndsAtStartOfLine,
385 std::move(FilesInPreamble));
Ilya Biryukov200b3282017-06-21 10:24:58 +0000386}
387
388PreambleBounds PrecompiledPreamble::getBounds() const {
389 return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
390}
391
Ilya Biryukov923e3382017-12-21 14:04:39 +0000392std::size_t PrecompiledPreamble::getSize() const {
393 switch (Storage.getKind()) {
394 case PCHStorage::Kind::Empty:
395 assert(false && "Calling getSize() on invalid PrecompiledPreamble. "
396 "Was it std::moved?");
397 return 0;
398 case PCHStorage::Kind::InMemory:
399 return Storage.asMemory().Data.size();
400 case PCHStorage::Kind::TempFile: {
401 uint64_t Result;
402 if (llvm::sys::fs::file_size(Storage.asFile().getFilePath(), Result))
403 return 0;
404
405 assert(Result <= std::numeric_limits<std::size_t>::max() &&
406 "file size did not fit into size_t");
407 return Result;
408 }
409 }
410 llvm_unreachable("Unhandled storage kind");
411}
412
Ilya Biryukov200b3282017-06-21 10:24:58 +0000413bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation,
414 const llvm::MemoryBuffer *MainFileBuffer,
415 PreambleBounds Bounds,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000416 llvm::vfs::FileSystem *VFS) const {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000417
418 assert(
419 Bounds.Size <= MainFileBuffer->getBufferSize() &&
420 "Buffer is too large. Bounds were calculated from a different buffer?");
421
422 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
423 PreprocessorOptions &PreprocessorOpts =
424 PreambleInvocation->getPreprocessorOpts();
425
Ilya Biryukov200b3282017-06-21 10:24:58 +0000426 // We've previously computed a preamble. Check whether we have the same
427 // preamble now that we did before, and that there's enough space in
428 // the main-file buffer within the precompiled preamble to fit the
429 // new main file.
430 if (PreambleBytes.size() != Bounds.Size ||
431 PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
Haojian Wua3b34572018-08-22 12:34:04 +0000432 !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
433 MainFileBuffer->getBuffer().begin()))
Ilya Biryukov200b3282017-06-21 10:24:58 +0000434 return false;
435 // The preamble has not changed. We may be able to re-use the precompiled
436 // preamble.
437
438 // Check that none of the files used by the preamble have changed.
439 // First, make a record of those files that have been overridden via
440 // remapping or unsaved_files.
441 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
442 for (const auto &R : PreprocessorOpts.RemappedFiles) {
Jonas Devliegherefc514902018-10-10 13:27:25 +0000443 llvm::vfs::Status Status;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000444 if (!moveOnNoError(VFS->status(R.second), Status)) {
445 // If we can't stat the file we're remapping to, assume that something
446 // horrible happened.
447 return false;
448 }
449
450 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
451 Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
452 }
453
454 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
Jonas Devliegherefc514902018-10-10 13:27:25 +0000455 llvm::vfs::Status Status;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000456 if (!moveOnNoError(VFS->status(RB.first), Status))
457 return false;
458
459 OverriddenFiles[Status.getUniqueID()] =
460 PreambleFileHash::createForMemoryBuffer(RB.second);
461 }
462
463 // Check whether anything has changed.
464 for (const auto &F : FilesInPreamble) {
Jonas Devliegherefc514902018-10-10 13:27:25 +0000465 llvm::vfs::Status Status;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000466 if (!moveOnNoError(VFS->status(F.first()), Status)) {
467 // If we can't stat the file, assume that something horrible happened.
468 return false;
469 }
470
471 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
472 OverriddenFiles.find(Status.getUniqueID());
473 if (Overridden != OverriddenFiles.end()) {
474 // This file was remapped; check whether the newly-mapped file
475 // matches up with the previous mapping.
476 if (Overridden->second != F.second)
477 return false;
478 continue;
479 }
480
481 // The file was not remapped; check whether it has changed on disk.
482 if (Status.getSize() != uint64_t(F.second.Size) ||
483 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
484 F.second.ModTime)
485 return false;
486 }
487 return true;
488}
489
490void PrecompiledPreamble::AddImplicitPreamble(
Jonas Devliegherefc514902018-10-10 13:27:25 +0000491 CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
Ilya Biryukov417085a2017-11-16 16:25:01 +0000492 llvm::MemoryBuffer *MainFileBuffer) const {
Ilya Biryukov4a8f7532018-01-18 15:16:53 +0000493 PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
494 configurePreamble(Bounds, CI, VFS, MainFileBuffer);
495}
Ilya Biryukov200b3282017-06-21 10:24:58 +0000496
Ilya Biryukov4a8f7532018-01-18 15:16:53 +0000497void PrecompiledPreamble::OverridePreamble(
Jonas Devliegherefc514902018-10-10 13:27:25 +0000498 CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
Ilya Biryukov4a8f7532018-01-18 15:16:53 +0000499 llvm::MemoryBuffer *MainFileBuffer) const {
500 auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), MainFileBuffer, 0);
501 configurePreamble(Bounds, CI, VFS, MainFileBuffer);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000502}
503
504PrecompiledPreamble::PrecompiledPreamble(
Ilya Biryukov417085a2017-11-16 16:25:01 +0000505 PCHStorage Storage, std::vector<char> PreambleBytes,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000506 bool PreambleEndsAtStartOfLine,
507 llvm::StringMap<PreambleFileHash> FilesInPreamble)
Ilya Biryukov417085a2017-11-16 16:25:01 +0000508 : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
Ilya Biryukov200b3282017-06-21 10:24:58 +0000509 PreambleBytes(std::move(PreambleBytes)),
Ilya Biryukov417085a2017-11-16 16:25:01 +0000510 PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
511 assert(this->Storage.getKind() != PCHStorage::Kind::Empty);
512}
Ilya Biryukov200b3282017-06-21 10:24:58 +0000513
514llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
515PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile() {
516 // FIXME: This is a hack so that we can override the preamble file during
517 // crash-recovery testing, which is the only case where the preamble files
518 // are not necessarily cleaned up.
519 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
520 if (TmpFile)
521 return TempPCHFile::createFromCustomPath(TmpFile);
522 return TempPCHFile::createInSystemTempDir("preamble", "pch");
523}
524
525llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
526PrecompiledPreamble::TempPCHFile::createInSystemTempDir(const Twine &Prefix,
527 StringRef Suffix) {
528 llvm::SmallString<64> File;
Ilya Biryukovb88de412017-08-10 16:10:40 +0000529 // Using a version of createTemporaryFile with a file descriptor guarantees
Ilya Biryukov923e3382017-12-21 14:04:39 +0000530 // that we would never get a race condition in a multi-threaded setting
531 // (i.e., multiple threads getting the same temporary path).
Ilya Biryukovb88de412017-08-10 16:10:40 +0000532 int FD;
Ilya Biryukov417085a2017-11-16 16:25:01 +0000533 auto EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, FD, File);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000534 if (EC)
535 return EC;
Ilya Biryukovb88de412017-08-10 16:10:40 +0000536 // We only needed to make sure the file exists, close the file right away.
537 llvm::sys::Process::SafelyCloseFileDescriptor(FD);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000538 return TempPCHFile(std::move(File).str());
539}
540
541llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
542PrecompiledPreamble::TempPCHFile::createFromCustomPath(const Twine &Path) {
543 return TempPCHFile(Path.str());
544}
545
546PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath)
547 : FilePath(std::move(FilePath)) {
548 TemporaryFiles::getInstance().addFile(*this->FilePath);
549}
550
551PrecompiledPreamble::TempPCHFile::TempPCHFile(TempPCHFile &&Other) {
552 FilePath = std::move(Other.FilePath);
553 Other.FilePath = None;
554}
555
556PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::TempPCHFile::
557operator=(TempPCHFile &&Other) {
558 RemoveFileIfPresent();
559
560 FilePath = std::move(Other.FilePath);
561 Other.FilePath = None;
562 return *this;
563}
564
565PrecompiledPreamble::TempPCHFile::~TempPCHFile() { RemoveFileIfPresent(); }
566
567void PrecompiledPreamble::TempPCHFile::RemoveFileIfPresent() {
568 if (FilePath) {
569 TemporaryFiles::getInstance().removeFile(*FilePath);
570 FilePath = None;
571 }
572}
573
574llvm::StringRef PrecompiledPreamble::TempPCHFile::getFilePath() const {
575 assert(FilePath && "TempPCHFile doesn't have a FilePath. Had it been moved?");
576 return *FilePath;
577}
578
Ilya Biryukov417085a2017-11-16 16:25:01 +0000579PrecompiledPreamble::PCHStorage::PCHStorage(TempPCHFile File)
580 : StorageKind(Kind::TempFile) {
581 new (&asFile()) TempPCHFile(std::move(File));
582}
583
584PrecompiledPreamble::PCHStorage::PCHStorage(InMemoryPreamble Memory)
585 : StorageKind(Kind::InMemory) {
586 new (&asMemory()) InMemoryPreamble(std::move(Memory));
587}
588
589PrecompiledPreamble::PCHStorage::PCHStorage(PCHStorage &&Other) : PCHStorage() {
590 *this = std::move(Other);
591}
592
593PrecompiledPreamble::PCHStorage &PrecompiledPreamble::PCHStorage::
594operator=(PCHStorage &&Other) {
595 destroy();
596
597 StorageKind = Other.StorageKind;
598 switch (StorageKind) {
599 case Kind::Empty:
600 // do nothing;
601 break;
602 case Kind::TempFile:
603 new (&asFile()) TempPCHFile(std::move(Other.asFile()));
604 break;
605 case Kind::InMemory:
606 new (&asMemory()) InMemoryPreamble(std::move(Other.asMemory()));
607 break;
608 }
609
610 Other.setEmpty();
611 return *this;
612}
613
614PrecompiledPreamble::PCHStorage::~PCHStorage() { destroy(); }
615
616PrecompiledPreamble::PCHStorage::Kind
617PrecompiledPreamble::PCHStorage::getKind() const {
618 return StorageKind;
619}
620
621PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::PCHStorage::asFile() {
622 assert(getKind() == Kind::TempFile);
623 return *reinterpret_cast<TempPCHFile *>(Storage.buffer);
624}
625
626const PrecompiledPreamble::TempPCHFile &
627PrecompiledPreamble::PCHStorage::asFile() const {
628 return const_cast<PCHStorage *>(this)->asFile();
629}
630
631PrecompiledPreamble::InMemoryPreamble &
632PrecompiledPreamble::PCHStorage::asMemory() {
633 assert(getKind() == Kind::InMemory);
634 return *reinterpret_cast<InMemoryPreamble *>(Storage.buffer);
635}
636
637const PrecompiledPreamble::InMemoryPreamble &
638PrecompiledPreamble::PCHStorage::asMemory() const {
639 return const_cast<PCHStorage *>(this)->asMemory();
640}
641
642void PrecompiledPreamble::PCHStorage::destroy() {
643 switch (StorageKind) {
644 case Kind::Empty:
645 return;
646 case Kind::TempFile:
647 asFile().~TempPCHFile();
648 return;
649 case Kind::InMemory:
650 asMemory().~InMemoryPreamble();
651 return;
652 }
653}
654
655void PrecompiledPreamble::PCHStorage::setEmpty() {
656 destroy();
657 StorageKind = Kind::Empty;
658}
659
Ilya Biryukov200b3282017-06-21 10:24:58 +0000660PrecompiledPreamble::PreambleFileHash
661PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
662 time_t ModTime) {
663 PreambleFileHash Result;
664 Result.Size = Size;
665 Result.ModTime = ModTime;
666 Result.MD5 = {};
667 return Result;
668}
669
670PrecompiledPreamble::PreambleFileHash
671PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
672 const llvm::MemoryBuffer *Buffer) {
673 PreambleFileHash Result;
674 Result.Size = Buffer->getBufferSize();
675 Result.ModTime = 0;
676
677 llvm::MD5 MD5Ctx;
678 MD5Ctx.update(Buffer->getBuffer().data());
679 MD5Ctx.final(Result.MD5);
680
681 return Result;
682}
683
Ilya Biryukov4a8f7532018-01-18 15:16:53 +0000684void PrecompiledPreamble::configurePreamble(
685 PreambleBounds Bounds, CompilerInvocation &CI,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000686 IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
Ilya Biryukov4a8f7532018-01-18 15:16:53 +0000687 llvm::MemoryBuffer *MainFileBuffer) const {
688 assert(VFS);
689
690 auto &PreprocessorOpts = CI.getPreprocessorOpts();
691
692 // Remap main file to point to MainFileBuffer.
693 auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
694 PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
695
696 // Configure ImpicitPCHInclude.
697 PreprocessorOpts.PrecompiledPreambleBytes.first = Bounds.Size;
698 PreprocessorOpts.PrecompiledPreambleBytes.second =
699 Bounds.PreambleEndsAtStartOfLine;
700 PreprocessorOpts.DisablePCHValidation = true;
701
702 setupPreambleStorage(Storage, PreprocessorOpts, VFS);
703}
704
Ilya Biryukov417085a2017-11-16 16:25:01 +0000705void PrecompiledPreamble::setupPreambleStorage(
706 const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000707 IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS) {
Ilya Biryukov417085a2017-11-16 16:25:01 +0000708 if (Storage.getKind() == PCHStorage::Kind::TempFile) {
709 const TempPCHFile &PCHFile = Storage.asFile();
710 PreprocessorOpts.ImplicitPCHInclude = PCHFile.getFilePath();
711
712 // Make sure we can access the PCH file even if we're using a VFS
Jonas Devliegherefc514902018-10-10 13:27:25 +0000713 IntrusiveRefCntPtr<llvm::vfs::FileSystem> RealFS =
714 llvm::vfs::getRealFileSystem();
Ilya Biryukov417085a2017-11-16 16:25:01 +0000715 auto PCHPath = PCHFile.getFilePath();
716 if (VFS == RealFS || VFS->exists(PCHPath))
717 return;
718 auto Buf = RealFS->getBufferForFile(PCHPath);
719 if (!Buf) {
720 // We can't read the file even from RealFS, this is clearly an error,
721 // but we'll just leave the current VFS as is and let clang's code
722 // figure out what to do with missing PCH.
723 return;
724 }
725
726 // We have a slight inconsistency here -- we're using the VFS to
727 // read files, but the PCH was generated in the real file system.
728 VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
729 } else {
730 assert(Storage.getKind() == PCHStorage::Kind::InMemory);
731 // For in-memory preamble, we have to provide a VFS overlay that makes it
732 // accessible.
733 StringRef PCHPath = getInMemoryPreamblePath();
734 PreprocessorOpts.ImplicitPCHInclude = PCHPath;
735
Ilya Biryukov8318f61b2017-11-24 13:12:38 +0000736 auto Buf = llvm::MemoryBuffer::getMemBuffer(Storage.asMemory().Data);
Ilya Biryukov417085a2017-11-16 16:25:01 +0000737 VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
738 }
739}
740
Ilya Biryukov1f8647d2017-12-20 16:48:56 +0000741void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
Ilya Biryukov200b3282017-06-21 10:24:58 +0000742void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
743void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
744void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
Ilya Biryukov41e90bc2017-12-15 11:27:51 +0000745std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
746 return nullptr;
747}
Kadir Cetinkaya9e012e82019-02-04 09:42:33 +0000748CommentHandler *PreambleCallbacks::getCommentHandler() { return nullptr; }
Ilya Biryukov200b3282017-06-21 10:24:58 +0000749
Alexandre Ganea51c93492018-08-29 14:28:04 +0000750static llvm::ManagedStatic<BuildPreambleErrorCategory> BuildPreambleErrCategory;
751
Ilya Biryukov200b3282017-06-21 10:24:58 +0000752std::error_code clang::make_error_code(BuildPreambleError Error) {
Alexandre Ganea51c93492018-08-29 14:28:04 +0000753 return std::error_code(static_cast<int>(Error), *BuildPreambleErrCategory);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000754}
755
756const char *BuildPreambleErrorCategory::name() const noexcept {
757 return "build-preamble.error";
758}
759
760std::string BuildPreambleErrorCategory::message(int condition) const {
761 switch (static_cast<BuildPreambleError>(condition)) {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000762 case BuildPreambleError::CouldntCreateTempFile:
763 return "Could not create temporary file for PCH";
764 case BuildPreambleError::CouldntCreateTargetInfo:
765 return "CreateTargetInfo() return null";
Ilya Biryukov200b3282017-06-21 10:24:58 +0000766 case BuildPreambleError::BeginSourceFileFailed:
767 return "BeginSourceFile() return an error";
768 case BuildPreambleError::CouldntEmitPCH:
769 return "Could not emit PCH";
770 }
771 llvm_unreachable("unexpected BuildPreambleError");
772}