blob: 1fe8bfcb7459400eec097e6f01b1abef9a40efd7 [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,
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000160 const Preprocessor &PP,
161 InMemoryModuleCache &ModuleCache,
162 StringRef isysroot,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000163 std::unique_ptr<raw_ostream> Out)
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000164 : PCHGenerator(PP, ModuleCache, "", isysroot,
165 std::make_shared<PCHBuffer>(),
Ilya Biryukov200b3282017-06-21 10:24:58 +0000166 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
167 /*AllowASTWithErrors=*/true),
168 Action(Action), Out(std::move(Out)) {}
169
170 bool HandleTopLevelDecl(DeclGroupRef DG) override {
171 Action.Callbacks.HandleTopLevelDecl(DG);
172 return true;
173 }
174
175 void HandleTranslationUnit(ASTContext &Ctx) override {
176 PCHGenerator::HandleTranslationUnit(Ctx);
177 if (!hasEmittedPCH())
178 return;
179
180 // Write the generated bitstream to "Out".
181 *Out << getPCH();
182 // Make sure it hits disk now.
183 Out->flush();
184 // Free the buffer.
185 llvm::SmallVector<char, 0> Empty;
186 getPCH() = std::move(Empty);
187
188 Action.setEmittedPreamblePCH(getWriter());
189 }
190
191private:
192 PrecompilePreambleAction &Action;
193 std::unique_ptr<raw_ostream> Out;
194};
195
196std::unique_ptr<ASTConsumer>
197PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000198 StringRef InFile) {
199 std::string Sysroot;
Ilya Biryukov417085a2017-11-16 16:25:01 +0000200 if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
201 return nullptr;
202
203 std::unique_ptr<llvm::raw_ostream> OS;
204 if (InMemStorage) {
205 OS = llvm::make_unique<llvm::raw_string_ostream>(*InMemStorage);
206 } else {
207 std::string OutputFile;
208 OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
209 }
Ilya Biryukov200b3282017-06-21 10:24:58 +0000210 if (!OS)
211 return nullptr;
212
213 if (!CI.getFrontendOpts().RelocatablePCH)
214 Sysroot.clear();
215
Ilya Biryukov200b3282017-06-21 10:24:58 +0000216 return llvm::make_unique<PrecompilePreambleConsumer>(
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000217 *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, std::move(OS));
Ilya Biryukov200b3282017-06-21 10:24:58 +0000218}
219
220template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
221 if (!Val)
222 return false;
223 Output = std::move(*Val);
224 return true;
225}
226
227} // namespace
228
229PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
230 llvm::MemoryBuffer *Buffer,
231 unsigned MaxLines) {
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000232 return Lexer::ComputePreamble(Buffer->getBuffer(), LangOpts, MaxLines);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000233}
234
235llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
236 const CompilerInvocation &Invocation,
237 const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000238 DiagnosticsEngine &Diagnostics,
239 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
Ilya Biryukov417085a2017-11-16 16:25:01 +0000240 std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000241 PreambleCallbacks &Callbacks) {
242 assert(VFS && "VFS is null");
243
Ilya Biryukov200b3282017-06-21 10:24:58 +0000244 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
245 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
246 PreprocessorOptions &PreprocessorOpts =
247 PreambleInvocation->getPreprocessorOpts();
248
Ilya Biryukov417085a2017-11-16 16:25:01 +0000249 llvm::Optional<TempPCHFile> TempFile;
250 if (!StoreInMemory) {
251 // Create a temporary file for the precompiled preamble. In rare
252 // circumstances, this can fail.
253 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> PreamblePCHFile =
254 PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile();
255 if (!PreamblePCHFile)
256 return BuildPreambleError::CouldntCreateTempFile;
257 TempFile = std::move(*PreamblePCHFile);
258 }
259
260 PCHStorage Storage = StoreInMemory ? PCHStorage(InMemoryPreamble())
261 : PCHStorage(std::move(*TempFile));
Ilya Biryukov200b3282017-06-21 10:24:58 +0000262
263 // Save the preamble text for later; we'll need to compare against it for
264 // subsequent reparses.
265 std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
266 MainFileBuffer->getBufferStart() +
267 Bounds.Size);
268 bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
269
270 // Tell the compiler invocation to generate a temporary precompiled header.
271 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Ilya Biryukov417085a2017-11-16 16:25:01 +0000272 FrontendOpts.OutputFile = StoreInMemory ? getInMemoryPreamblePath()
273 : Storage.asFile().getFilePath();
Ilya Biryukov200b3282017-06-21 10:24:58 +0000274 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
275 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Ilya Biryukoveb1ec872017-10-09 16:52:12 +0000276 // Inform preprocessor to record conditional stack when building the preamble.
277 PreprocessorOpts.GeneratePreamble = true;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000278
279 // Create the compiler instance to use for building the precompiled preamble.
280 std::unique_ptr<CompilerInstance> Clang(
281 new CompilerInstance(std::move(PCHContainerOps)));
282
283 // Recover resources if we crash before exiting this method.
284 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
285 Clang.get());
286
287 Clang->setInvocation(std::move(PreambleInvocation));
288 Clang->setDiagnostics(&Diagnostics);
289
290 // Create the target instance.
291 Clang->setTarget(TargetInfo::CreateTargetInfo(
292 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
293 if (!Clang->hasTarget())
294 return BuildPreambleError::CouldntCreateTargetInfo;
295
296 // Inform the target of the language options.
297 //
298 // FIXME: We shouldn't need to do this, the target should be immutable once
299 // created. This complexity should be lifted elsewhere.
300 Clang->getTarget().adjust(Clang->getLangOpts());
301
Ilya Biryukov29175262019-05-22 12:50:01 +0000302 if (Clang->getFrontendOpts().Inputs.size() != 1 ||
303 Clang->getFrontendOpts().Inputs[0].getKind().getFormat() !=
304 InputKind::Source ||
305 Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() ==
306 InputKind::LLVM_IR) {
307 return BuildPreambleError::BadInputs;
308 }
Ilya Biryukov200b3282017-06-21 10:24:58 +0000309
310 // Clear out old caches and data.
311 Diagnostics.Reset();
312 ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
313
314 VFS =
315 createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000316
317 // Create a file manager object to provide access to and cache the filesystem.
318 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
319
320 // Create the source manager.
321 Clang->setSourceManager(
322 new SourceManager(Diagnostics, Clang->getFileManager()));
323
Ilya Biryukove5801b02018-07-09 09:07:01 +0000324 auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>();
Ilya Biryukov200b3282017-06-21 10:24:58 +0000325 Clang->addDependencyCollector(PreambleDepCollector);
326
327 // Remap the main source file to the preamble buffer.
328 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
329 auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
330 MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
331 if (PreprocessorOpts.RetainRemappedFileBuffers) {
332 // MainFileBuffer will be deleted by unique_ptr after leaving the method.
333 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
334 } else {
335 // In that case, remapped buffer will be deleted by CompilerInstance on
336 // BeginSourceFile, so we call release() to avoid double deletion.
337 PreprocessorOpts.addRemappedFile(MainFilePath,
338 PreambleInputBuffer.release());
339 }
340
341 std::unique_ptr<PrecompilePreambleAction> Act;
Ilya Biryukov417085a2017-11-16 16:25:01 +0000342 Act.reset(new PrecompilePreambleAction(
343 StoreInMemory ? &Storage.asMemory().Data : nullptr, Callbacks));
Ilya Biryukov1f8647d2017-12-20 16:48:56 +0000344 Callbacks.BeforeExecute(*Clang);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000345 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
346 return BuildPreambleError::BeginSourceFileFailed;
347
Ilya Biryukov41e90bc2017-12-15 11:27:51 +0000348 std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
349 Callbacks.createPPCallbacks();
350 if (DelegatedPPCallbacks)
351 Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
Kadir Cetinkaya9e012e82019-02-04 09:42:33 +0000352 if (auto CommentHandler = Callbacks.getCommentHandler())
353 Clang->getPreprocessor().addCommentHandler(CommentHandler);
Ilya Biryukov41e90bc2017-12-15 11:27:51 +0000354
Ilya Biryukov200b3282017-06-21 10:24:58 +0000355 Act->Execute();
356
357 // Run the callbacks.
358 Callbacks.AfterExecute(*Clang);
359
360 Act->EndSourceFile();
361
362 if (!Act->hasEmittedPreamblePCH())
363 return BuildPreambleError::CouldntEmitPCH;
364
365 // Keep track of all of the files that the source manager knows about,
366 // so we can verify whether they have changed or not.
367 llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
368
369 SourceManager &SourceMgr = Clang->getSourceManager();
370 for (auto &Filename : PreambleDepCollector->getDependencies()) {
371 const FileEntry *File = Clang->getFileManager().getFile(Filename);
372 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
373 continue;
374 if (time_t ModTime = File->getModificationTime()) {
375 FilesInPreamble[File->getName()] =
376 PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
377 ModTime);
378 } else {
Nico Weber04347d82019-04-04 21:06:41 +0000379 const llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000380 FilesInPreamble[File->getName()] =
381 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
382 }
383 }
384
Ilya Biryukov417085a2017-11-16 16:25:01 +0000385 return PrecompiledPreamble(std::move(Storage), std::move(PreambleBytes),
386 PreambleEndsAtStartOfLine,
387 std::move(FilesInPreamble));
Ilya Biryukov200b3282017-06-21 10:24:58 +0000388}
389
390PreambleBounds PrecompiledPreamble::getBounds() const {
391 return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
392}
393
Ilya Biryukov923e3382017-12-21 14:04:39 +0000394std::size_t PrecompiledPreamble::getSize() const {
395 switch (Storage.getKind()) {
396 case PCHStorage::Kind::Empty:
397 assert(false && "Calling getSize() on invalid PrecompiledPreamble. "
398 "Was it std::moved?");
399 return 0;
400 case PCHStorage::Kind::InMemory:
401 return Storage.asMemory().Data.size();
402 case PCHStorage::Kind::TempFile: {
403 uint64_t Result;
404 if (llvm::sys::fs::file_size(Storage.asFile().getFilePath(), Result))
405 return 0;
406
407 assert(Result <= std::numeric_limits<std::size_t>::max() &&
408 "file size did not fit into size_t");
409 return Result;
410 }
411 }
412 llvm_unreachable("Unhandled storage kind");
413}
414
Ilya Biryukov200b3282017-06-21 10:24:58 +0000415bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation,
416 const llvm::MemoryBuffer *MainFileBuffer,
417 PreambleBounds Bounds,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000418 llvm::vfs::FileSystem *VFS) const {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000419
420 assert(
421 Bounds.Size <= MainFileBuffer->getBufferSize() &&
422 "Buffer is too large. Bounds were calculated from a different buffer?");
423
424 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
425 PreprocessorOptions &PreprocessorOpts =
426 PreambleInvocation->getPreprocessorOpts();
427
Ilya Biryukov200b3282017-06-21 10:24:58 +0000428 // We've previously computed a preamble. Check whether we have the same
429 // preamble now that we did before, and that there's enough space in
430 // the main-file buffer within the precompiled preamble to fit the
431 // new main file.
432 if (PreambleBytes.size() != Bounds.Size ||
433 PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
Haojian Wua3b34572018-08-22 12:34:04 +0000434 !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
435 MainFileBuffer->getBuffer().begin()))
Ilya Biryukov200b3282017-06-21 10:24:58 +0000436 return false;
437 // The preamble has not changed. We may be able to re-use the precompiled
438 // preamble.
439
440 // Check that none of the files used by the preamble have changed.
441 // First, make a record of those files that have been overridden via
442 // remapping or unsaved_files.
443 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
444 for (const auto &R : PreprocessorOpts.RemappedFiles) {
Jonas Devliegherefc514902018-10-10 13:27:25 +0000445 llvm::vfs::Status Status;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000446 if (!moveOnNoError(VFS->status(R.second), Status)) {
447 // If we can't stat the file we're remapping to, assume that something
448 // horrible happened.
449 return false;
450 }
451
452 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
453 Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
454 }
455
Nikolai Kosjar295c19e2019-05-21 07:26:59 +0000456 // OverridenFileBuffers tracks only the files not found in VFS.
457 llvm::StringMap<PreambleFileHash> OverridenFileBuffers;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000458 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
Nikolai Kosjar295c19e2019-05-21 07:26:59 +0000459 const PrecompiledPreamble::PreambleFileHash PreambleHash =
Ilya Biryukov200b3282017-06-21 10:24:58 +0000460 PreambleFileHash::createForMemoryBuffer(RB.second);
Nikolai Kosjar295c19e2019-05-21 07:26:59 +0000461 llvm::vfs::Status Status;
462 if (moveOnNoError(VFS->status(RB.first), Status))
463 OverriddenFiles[Status.getUniqueID()] = PreambleHash;
464 else
465 OverridenFileBuffers[RB.first] = PreambleHash;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000466 }
467
468 // Check whether anything has changed.
469 for (const auto &F : FilesInPreamble) {
Nikolai Kosjar295c19e2019-05-21 07:26:59 +0000470 auto OverridenFileBuffer = OverridenFileBuffers.find(F.first());
471 if (OverridenFileBuffer != OverridenFileBuffers.end()) {
472 // The file's buffer was remapped and the file was not found in VFS.
473 // Check whether it matches up with the previous mapping.
474 if (OverridenFileBuffer->second != F.second)
475 return false;
476 continue;
477 }
478
Jonas Devliegherefc514902018-10-10 13:27:25 +0000479 llvm::vfs::Status Status;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000480 if (!moveOnNoError(VFS->status(F.first()), Status)) {
Nikolai Kosjar295c19e2019-05-21 07:26:59 +0000481 // If the file's buffer is not remapped and we can't stat it,
482 // assume that something horrible happened.
Ilya Biryukov200b3282017-06-21 10:24:58 +0000483 return false;
484 }
485
486 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
487 OverriddenFiles.find(Status.getUniqueID());
488 if (Overridden != OverriddenFiles.end()) {
489 // This file was remapped; check whether the newly-mapped file
490 // matches up with the previous mapping.
491 if (Overridden->second != F.second)
492 return false;
493 continue;
494 }
495
Nikolai Kosjar295c19e2019-05-21 07:26:59 +0000496 // Neither the file's buffer nor the file itself was remapped;
497 // check whether it has changed on disk.
Ilya Biryukov200b3282017-06-21 10:24:58 +0000498 if (Status.getSize() != uint64_t(F.second.Size) ||
499 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
500 F.second.ModTime)
501 return false;
502 }
503 return true;
504}
505
506void PrecompiledPreamble::AddImplicitPreamble(
Jonas Devliegherefc514902018-10-10 13:27:25 +0000507 CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
Ilya Biryukov417085a2017-11-16 16:25:01 +0000508 llvm::MemoryBuffer *MainFileBuffer) const {
Ilya Biryukov4a8f7532018-01-18 15:16:53 +0000509 PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
510 configurePreamble(Bounds, CI, VFS, MainFileBuffer);
511}
Ilya Biryukov200b3282017-06-21 10:24:58 +0000512
Ilya Biryukov4a8f7532018-01-18 15:16:53 +0000513void PrecompiledPreamble::OverridePreamble(
Jonas Devliegherefc514902018-10-10 13:27:25 +0000514 CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
Ilya Biryukov4a8f7532018-01-18 15:16:53 +0000515 llvm::MemoryBuffer *MainFileBuffer) const {
516 auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), MainFileBuffer, 0);
517 configurePreamble(Bounds, CI, VFS, MainFileBuffer);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000518}
519
520PrecompiledPreamble::PrecompiledPreamble(
Ilya Biryukov417085a2017-11-16 16:25:01 +0000521 PCHStorage Storage, std::vector<char> PreambleBytes,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000522 bool PreambleEndsAtStartOfLine,
523 llvm::StringMap<PreambleFileHash> FilesInPreamble)
Ilya Biryukov417085a2017-11-16 16:25:01 +0000524 : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
Ilya Biryukov200b3282017-06-21 10:24:58 +0000525 PreambleBytes(std::move(PreambleBytes)),
Ilya Biryukov417085a2017-11-16 16:25:01 +0000526 PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
527 assert(this->Storage.getKind() != PCHStorage::Kind::Empty);
528}
Ilya Biryukov200b3282017-06-21 10:24:58 +0000529
530llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
531PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile() {
532 // FIXME: This is a hack so that we can override the preamble file during
533 // crash-recovery testing, which is the only case where the preamble files
534 // are not necessarily cleaned up.
535 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
536 if (TmpFile)
537 return TempPCHFile::createFromCustomPath(TmpFile);
538 return TempPCHFile::createInSystemTempDir("preamble", "pch");
539}
540
541llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
542PrecompiledPreamble::TempPCHFile::createInSystemTempDir(const Twine &Prefix,
543 StringRef Suffix) {
544 llvm::SmallString<64> File;
Ilya Biryukovb88de412017-08-10 16:10:40 +0000545 // Using a version of createTemporaryFile with a file descriptor guarantees
Ilya Biryukov923e3382017-12-21 14:04:39 +0000546 // that we would never get a race condition in a multi-threaded setting
547 // (i.e., multiple threads getting the same temporary path).
Ilya Biryukovb88de412017-08-10 16:10:40 +0000548 int FD;
Ilya Biryukov417085a2017-11-16 16:25:01 +0000549 auto EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, FD, File);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000550 if (EC)
551 return EC;
Ilya Biryukovb88de412017-08-10 16:10:40 +0000552 // We only needed to make sure the file exists, close the file right away.
553 llvm::sys::Process::SafelyCloseFileDescriptor(FD);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000554 return TempPCHFile(std::move(File).str());
555}
556
557llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
558PrecompiledPreamble::TempPCHFile::createFromCustomPath(const Twine &Path) {
559 return TempPCHFile(Path.str());
560}
561
562PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath)
563 : FilePath(std::move(FilePath)) {
564 TemporaryFiles::getInstance().addFile(*this->FilePath);
565}
566
567PrecompiledPreamble::TempPCHFile::TempPCHFile(TempPCHFile &&Other) {
568 FilePath = std::move(Other.FilePath);
569 Other.FilePath = None;
570}
571
572PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::TempPCHFile::
573operator=(TempPCHFile &&Other) {
574 RemoveFileIfPresent();
575
576 FilePath = std::move(Other.FilePath);
577 Other.FilePath = None;
578 return *this;
579}
580
581PrecompiledPreamble::TempPCHFile::~TempPCHFile() { RemoveFileIfPresent(); }
582
583void PrecompiledPreamble::TempPCHFile::RemoveFileIfPresent() {
584 if (FilePath) {
585 TemporaryFiles::getInstance().removeFile(*FilePath);
586 FilePath = None;
587 }
588}
589
590llvm::StringRef PrecompiledPreamble::TempPCHFile::getFilePath() const {
591 assert(FilePath && "TempPCHFile doesn't have a FilePath. Had it been moved?");
592 return *FilePath;
593}
594
Ilya Biryukov417085a2017-11-16 16:25:01 +0000595PrecompiledPreamble::PCHStorage::PCHStorage(TempPCHFile File)
596 : StorageKind(Kind::TempFile) {
597 new (&asFile()) TempPCHFile(std::move(File));
598}
599
600PrecompiledPreamble::PCHStorage::PCHStorage(InMemoryPreamble Memory)
601 : StorageKind(Kind::InMemory) {
602 new (&asMemory()) InMemoryPreamble(std::move(Memory));
603}
604
605PrecompiledPreamble::PCHStorage::PCHStorage(PCHStorage &&Other) : PCHStorage() {
606 *this = std::move(Other);
607}
608
609PrecompiledPreamble::PCHStorage &PrecompiledPreamble::PCHStorage::
610operator=(PCHStorage &&Other) {
611 destroy();
612
613 StorageKind = Other.StorageKind;
614 switch (StorageKind) {
615 case Kind::Empty:
616 // do nothing;
617 break;
618 case Kind::TempFile:
619 new (&asFile()) TempPCHFile(std::move(Other.asFile()));
620 break;
621 case Kind::InMemory:
622 new (&asMemory()) InMemoryPreamble(std::move(Other.asMemory()));
623 break;
624 }
625
626 Other.setEmpty();
627 return *this;
628}
629
630PrecompiledPreamble::PCHStorage::~PCHStorage() { destroy(); }
631
632PrecompiledPreamble::PCHStorage::Kind
633PrecompiledPreamble::PCHStorage::getKind() const {
634 return StorageKind;
635}
636
637PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::PCHStorage::asFile() {
638 assert(getKind() == Kind::TempFile);
639 return *reinterpret_cast<TempPCHFile *>(Storage.buffer);
640}
641
642const PrecompiledPreamble::TempPCHFile &
643PrecompiledPreamble::PCHStorage::asFile() const {
644 return const_cast<PCHStorage *>(this)->asFile();
645}
646
647PrecompiledPreamble::InMemoryPreamble &
648PrecompiledPreamble::PCHStorage::asMemory() {
649 assert(getKind() == Kind::InMemory);
650 return *reinterpret_cast<InMemoryPreamble *>(Storage.buffer);
651}
652
653const PrecompiledPreamble::InMemoryPreamble &
654PrecompiledPreamble::PCHStorage::asMemory() const {
655 return const_cast<PCHStorage *>(this)->asMemory();
656}
657
658void PrecompiledPreamble::PCHStorage::destroy() {
659 switch (StorageKind) {
660 case Kind::Empty:
661 return;
662 case Kind::TempFile:
663 asFile().~TempPCHFile();
664 return;
665 case Kind::InMemory:
666 asMemory().~InMemoryPreamble();
667 return;
668 }
669}
670
671void PrecompiledPreamble::PCHStorage::setEmpty() {
672 destroy();
673 StorageKind = Kind::Empty;
674}
675
Ilya Biryukov200b3282017-06-21 10:24:58 +0000676PrecompiledPreamble::PreambleFileHash
677PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
678 time_t ModTime) {
679 PreambleFileHash Result;
680 Result.Size = Size;
681 Result.ModTime = ModTime;
682 Result.MD5 = {};
683 return Result;
684}
685
686PrecompiledPreamble::PreambleFileHash
687PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
688 const llvm::MemoryBuffer *Buffer) {
689 PreambleFileHash Result;
690 Result.Size = Buffer->getBufferSize();
691 Result.ModTime = 0;
692
693 llvm::MD5 MD5Ctx;
694 MD5Ctx.update(Buffer->getBuffer().data());
695 MD5Ctx.final(Result.MD5);
696
697 return Result;
698}
699
Ilya Biryukov4a8f7532018-01-18 15:16:53 +0000700void PrecompiledPreamble::configurePreamble(
701 PreambleBounds Bounds, CompilerInvocation &CI,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000702 IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
Ilya Biryukov4a8f7532018-01-18 15:16:53 +0000703 llvm::MemoryBuffer *MainFileBuffer) const {
704 assert(VFS);
705
706 auto &PreprocessorOpts = CI.getPreprocessorOpts();
707
708 // Remap main file to point to MainFileBuffer.
709 auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
710 PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
711
712 // Configure ImpicitPCHInclude.
713 PreprocessorOpts.PrecompiledPreambleBytes.first = Bounds.Size;
714 PreprocessorOpts.PrecompiledPreambleBytes.second =
715 Bounds.PreambleEndsAtStartOfLine;
716 PreprocessorOpts.DisablePCHValidation = true;
717
718 setupPreambleStorage(Storage, PreprocessorOpts, VFS);
719}
720
Ilya Biryukov417085a2017-11-16 16:25:01 +0000721void PrecompiledPreamble::setupPreambleStorage(
722 const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000723 IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS) {
Ilya Biryukov417085a2017-11-16 16:25:01 +0000724 if (Storage.getKind() == PCHStorage::Kind::TempFile) {
725 const TempPCHFile &PCHFile = Storage.asFile();
726 PreprocessorOpts.ImplicitPCHInclude = PCHFile.getFilePath();
727
728 // Make sure we can access the PCH file even if we're using a VFS
Jonas Devliegherefc514902018-10-10 13:27:25 +0000729 IntrusiveRefCntPtr<llvm::vfs::FileSystem> RealFS =
730 llvm::vfs::getRealFileSystem();
Ilya Biryukov417085a2017-11-16 16:25:01 +0000731 auto PCHPath = PCHFile.getFilePath();
732 if (VFS == RealFS || VFS->exists(PCHPath))
733 return;
734 auto Buf = RealFS->getBufferForFile(PCHPath);
735 if (!Buf) {
736 // We can't read the file even from RealFS, this is clearly an error,
737 // but we'll just leave the current VFS as is and let clang's code
738 // figure out what to do with missing PCH.
739 return;
740 }
741
742 // We have a slight inconsistency here -- we're using the VFS to
743 // read files, but the PCH was generated in the real file system.
744 VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
745 } else {
746 assert(Storage.getKind() == PCHStorage::Kind::InMemory);
747 // For in-memory preamble, we have to provide a VFS overlay that makes it
748 // accessible.
749 StringRef PCHPath = getInMemoryPreamblePath();
750 PreprocessorOpts.ImplicitPCHInclude = PCHPath;
751
Ilya Biryukov8318f61b2017-11-24 13:12:38 +0000752 auto Buf = llvm::MemoryBuffer::getMemBuffer(Storage.asMemory().Data);
Ilya Biryukov417085a2017-11-16 16:25:01 +0000753 VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
754 }
755}
756
Ilya Biryukov1f8647d2017-12-20 16:48:56 +0000757void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
Ilya Biryukov200b3282017-06-21 10:24:58 +0000758void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
759void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
760void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
Ilya Biryukov41e90bc2017-12-15 11:27:51 +0000761std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
762 return nullptr;
763}
Kadir Cetinkaya9e012e82019-02-04 09:42:33 +0000764CommentHandler *PreambleCallbacks::getCommentHandler() { return nullptr; }
Ilya Biryukov200b3282017-06-21 10:24:58 +0000765
Alexandre Ganea51c93492018-08-29 14:28:04 +0000766static llvm::ManagedStatic<BuildPreambleErrorCategory> BuildPreambleErrCategory;
767
Ilya Biryukov200b3282017-06-21 10:24:58 +0000768std::error_code clang::make_error_code(BuildPreambleError Error) {
Alexandre Ganea51c93492018-08-29 14:28:04 +0000769 return std::error_code(static_cast<int>(Error), *BuildPreambleErrCategory);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000770}
771
772const char *BuildPreambleErrorCategory::name() const noexcept {
773 return "build-preamble.error";
774}
775
776std::string BuildPreambleErrorCategory::message(int condition) const {
777 switch (static_cast<BuildPreambleError>(condition)) {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000778 case BuildPreambleError::CouldntCreateTempFile:
779 return "Could not create temporary file for PCH";
780 case BuildPreambleError::CouldntCreateTargetInfo:
781 return "CreateTargetInfo() return null";
Ilya Biryukov200b3282017-06-21 10:24:58 +0000782 case BuildPreambleError::BeginSourceFileFailed:
783 return "BeginSourceFile() return an error";
784 case BuildPreambleError::CouldntEmitPCH:
785 return "Could not emit PCH";
Ilya Biryukov29175262019-05-22 12:50:01 +0000786 case BuildPreambleError::BadInputs:
787 return "Command line arguments must contain exactly one source file";
Ilya Biryukov200b3282017-06-21 10:24:58 +0000788 }
789 llvm_unreachable("unexpected BuildPreambleError");
790}