blob: f933ba6cec01255680750ea5aa963e2d04cf2e93 [file] [log] [blame]
Ilya Biryukov200b3282017-06-21 10:24:58 +00001//===--- PrecompiledPreamble.cpp - Build precompiled preambles --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Helper class to build precompiled preamble.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/PrecompiledPreamble.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/Basic/TargetInfo.h"
17#include "clang/Basic/VirtualFileSystem.h"
18#include "clang/Frontend/CompilerInstance.h"
19#include "clang/Frontend/CompilerInvocation.h"
20#include "clang/Frontend/FrontendActions.h"
21#include "clang/Frontend/FrontendOptions.h"
22#include "clang/Lex/Lexer.h"
23#include "clang/Lex/PreprocessorOptions.h"
24#include "clang/Serialization/ASTWriter.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/StringSet.h"
Ilya Biryukovdd9ea752017-11-17 10:09:02 +000027#include "llvm/Config/llvm-config.h"
Ilya Biryukov200b3282017-06-21 10:24:58 +000028#include "llvm/Support/CrashRecoveryContext.h"
29#include "llvm/Support/FileSystem.h"
30#include "llvm/Support/Mutex.h"
31#include "llvm/Support/MutexGuard.h"
Ilya Biryukovb88de412017-08-10 16:10:40 +000032#include "llvm/Support/Process.h"
Ilya Biryukov200b3282017-06-21 10:24:58 +000033
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___";
43#elif defined(LLVM_ON_WIN32)
44 return "C:\\__clang_tmp\\___clang_inmemory_preamble___";
45#else
46#warning "Unknown platform. Defaulting to UNIX-style paths for in-memory PCHs"
47 return "/__clang_tmp/___clang_inmemory_preamble___";
48#endif
49}
50
51IntrusiveRefCntPtr<vfs::FileSystem>
52createVFSOverlayForPreamblePCH(StringRef PCHFilename,
53 std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,
54 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
55 // We want only the PCH file from the real filesystem to be available,
56 // so we create an in-memory VFS with just that and overlay it on top.
57 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> PCHFS(
58 new vfs::InMemoryFileSystem());
59 PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer));
60 IntrusiveRefCntPtr<vfs::OverlayFileSystem> Overlay(
61 new vfs::OverlayFileSystem(VFS));
62 Overlay->pushOverlay(PCHFS);
63 return Overlay;
64}
65
Ilya Biryukov200b3282017-06-21 10:24:58 +000066/// Keeps a track of files to be deleted in destructor.
67class TemporaryFiles {
68public:
69 // A static instance to be used by all clients.
70 static TemporaryFiles &getInstance();
71
72private:
73 // Disallow constructing the class directly.
74 TemporaryFiles() = default;
75 // Disallow copy.
76 TemporaryFiles(const TemporaryFiles &) = delete;
77
78public:
79 ~TemporaryFiles();
80
81 /// Adds \p File to a set of tracked files.
82 void addFile(StringRef File);
83
84 /// Remove \p File from disk and from the set of tracked files.
85 void removeFile(StringRef File);
86
87private:
88 llvm::sys::SmartMutex<false> Mutex;
89 llvm::StringSet<> Files;
90};
91
92TemporaryFiles &TemporaryFiles::getInstance() {
93 static TemporaryFiles Instance;
94 return Instance;
95}
96
97TemporaryFiles::~TemporaryFiles() {
98 llvm::MutexGuard Guard(Mutex);
99 for (const auto &File : Files)
100 llvm::sys::fs::remove(File.getKey());
101}
102
103void TemporaryFiles::addFile(StringRef File) {
104 llvm::MutexGuard Guard(Mutex);
105 auto IsInserted = Files.insert(File).second;
Haojian Wu53dd6442017-06-21 11:26:58 +0000106 (void)IsInserted;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000107 assert(IsInserted && "File has already been added");
108}
109
110void TemporaryFiles::removeFile(StringRef File) {
111 llvm::MutexGuard Guard(Mutex);
112 auto WasPresent = Files.erase(File);
Haojian Wu53dd6442017-06-21 11:26:58 +0000113 (void)WasPresent;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000114 assert(WasPresent && "File was not tracked");
115 llvm::sys::fs::remove(File);
116}
117
Ilya Biryukov200b3282017-06-21 10:24:58 +0000118class PrecompilePreambleAction : public ASTFrontendAction {
119public:
Ilya Biryukov417085a2017-11-16 16:25:01 +0000120 PrecompilePreambleAction(std::string *InMemStorage,
121 PreambleCallbacks &Callbacks)
122 : InMemStorage(InMemStorage), Callbacks(Callbacks) {}
Ilya Biryukov200b3282017-06-21 10:24:58 +0000123
124 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
125 StringRef InFile) override;
126
127 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
128
129 void setEmittedPreamblePCH(ASTWriter &Writer) {
130 this->HasEmittedPreamblePCH = true;
131 Callbacks.AfterPCHEmitted(Writer);
132 }
133
134 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
135 bool hasCodeCompletionSupport() const override { return false; }
136 bool hasASTFileSupport() const override { return false; }
137 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
138
139private:
140 friend class PrecompilePreambleConsumer;
141
142 bool HasEmittedPreamblePCH = false;
Ilya Biryukov417085a2017-11-16 16:25:01 +0000143 std::string *InMemStorage;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000144 PreambleCallbacks &Callbacks;
145};
146
147class PrecompilePreambleConsumer : public PCHGenerator {
148public:
149 PrecompilePreambleConsumer(PrecompilePreambleAction &Action,
150 const Preprocessor &PP, StringRef isysroot,
151 std::unique_ptr<raw_ostream> Out)
152 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(),
153 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
154 /*AllowASTWithErrors=*/true),
155 Action(Action), Out(std::move(Out)) {}
156
157 bool HandleTopLevelDecl(DeclGroupRef DG) override {
158 Action.Callbacks.HandleTopLevelDecl(DG);
159 return true;
160 }
161
162 void HandleTranslationUnit(ASTContext &Ctx) override {
163 PCHGenerator::HandleTranslationUnit(Ctx);
164 if (!hasEmittedPCH())
165 return;
166
167 // Write the generated bitstream to "Out".
168 *Out << getPCH();
169 // Make sure it hits disk now.
170 Out->flush();
171 // Free the buffer.
172 llvm::SmallVector<char, 0> Empty;
173 getPCH() = std::move(Empty);
174
175 Action.setEmittedPreamblePCH(getWriter());
176 }
177
178private:
179 PrecompilePreambleAction &Action;
180 std::unique_ptr<raw_ostream> Out;
181};
182
183std::unique_ptr<ASTConsumer>
184PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000185 StringRef InFile) {
186 std::string Sysroot;
Ilya Biryukov417085a2017-11-16 16:25:01 +0000187 if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
188 return nullptr;
189
190 std::unique_ptr<llvm::raw_ostream> OS;
191 if (InMemStorage) {
192 OS = llvm::make_unique<llvm::raw_string_ostream>(*InMemStorage);
193 } else {
194 std::string OutputFile;
195 OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
196 }
Ilya Biryukov200b3282017-06-21 10:24:58 +0000197 if (!OS)
198 return nullptr;
199
200 if (!CI.getFrontendOpts().RelocatablePCH)
201 Sysroot.clear();
202
Ilya Biryukov200b3282017-06-21 10:24:58 +0000203 return llvm::make_unique<PrecompilePreambleConsumer>(
204 *this, CI.getPreprocessor(), Sysroot, std::move(OS));
205}
206
207template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
208 if (!Val)
209 return false;
210 Output = std::move(*Val);
211 return true;
212}
213
214} // namespace
215
216PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
217 llvm::MemoryBuffer *Buffer,
218 unsigned MaxLines) {
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000219 return Lexer::ComputePreamble(Buffer->getBuffer(), LangOpts, MaxLines);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000220}
221
222llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
223 const CompilerInvocation &Invocation,
224 const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
225 DiagnosticsEngine &Diagnostics, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
Ilya Biryukov417085a2017-11-16 16:25:01 +0000226 std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000227 PreambleCallbacks &Callbacks) {
228 assert(VFS && "VFS is null");
229
230 if (!Bounds.Size)
231 return BuildPreambleError::PreambleIsEmpty;
232
233 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
234 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
235 PreprocessorOptions &PreprocessorOpts =
236 PreambleInvocation->getPreprocessorOpts();
237
Ilya Biryukov417085a2017-11-16 16:25:01 +0000238 llvm::Optional<TempPCHFile> TempFile;
239 if (!StoreInMemory) {
240 // Create a temporary file for the precompiled preamble. In rare
241 // circumstances, this can fail.
242 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> PreamblePCHFile =
243 PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile();
244 if (!PreamblePCHFile)
245 return BuildPreambleError::CouldntCreateTempFile;
246 TempFile = std::move(*PreamblePCHFile);
247 }
248
249 PCHStorage Storage = StoreInMemory ? PCHStorage(InMemoryPreamble())
250 : PCHStorage(std::move(*TempFile));
Ilya Biryukov200b3282017-06-21 10:24:58 +0000251
252 // Save the preamble text for later; we'll need to compare against it for
253 // subsequent reparses.
254 std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
255 MainFileBuffer->getBufferStart() +
256 Bounds.Size);
257 bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
258
259 // Tell the compiler invocation to generate a temporary precompiled header.
260 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Ilya Biryukov417085a2017-11-16 16:25:01 +0000261 FrontendOpts.OutputFile = StoreInMemory ? getInMemoryPreamblePath()
262 : Storage.asFile().getFilePath();
Ilya Biryukov200b3282017-06-21 10:24:58 +0000263 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
264 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Ilya Biryukoveb1ec872017-10-09 16:52:12 +0000265 // Inform preprocessor to record conditional stack when building the preamble.
266 PreprocessorOpts.GeneratePreamble = true;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000267
268 // Create the compiler instance to use for building the precompiled preamble.
269 std::unique_ptr<CompilerInstance> Clang(
270 new CompilerInstance(std::move(PCHContainerOps)));
271
272 // Recover resources if we crash before exiting this method.
273 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
274 Clang.get());
275
276 Clang->setInvocation(std::move(PreambleInvocation));
277 Clang->setDiagnostics(&Diagnostics);
278
279 // Create the target instance.
280 Clang->setTarget(TargetInfo::CreateTargetInfo(
281 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
282 if (!Clang->hasTarget())
283 return BuildPreambleError::CouldntCreateTargetInfo;
284
285 // Inform the target of the language options.
286 //
287 // FIXME: We shouldn't need to do this, the target should be immutable once
288 // created. This complexity should be lifted elsewhere.
289 Clang->getTarget().adjust(Clang->getLangOpts());
290
291 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
292 "Invocation must have exactly one source file!");
293 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
294 InputKind::Source &&
295 "FIXME: AST inputs not yet supported here!");
296 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
297 InputKind::LLVM_IR &&
298 "IR inputs not support here!");
299
300 // Clear out old caches and data.
301 Diagnostics.Reset();
302 ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
303
304 VFS =
305 createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
306 if (!VFS)
307 return BuildPreambleError::CouldntCreateVFSOverlay;
308
309 // Create a file manager object to provide access to and cache the filesystem.
310 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
311
312 // Create the source manager.
313 Clang->setSourceManager(
314 new SourceManager(Diagnostics, Clang->getFileManager()));
315
316 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
317 Clang->addDependencyCollector(PreambleDepCollector);
318
319 // Remap the main source file to the preamble buffer.
320 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
321 auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
322 MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
323 if (PreprocessorOpts.RetainRemappedFileBuffers) {
324 // MainFileBuffer will be deleted by unique_ptr after leaving the method.
325 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
326 } else {
327 // In that case, remapped buffer will be deleted by CompilerInstance on
328 // BeginSourceFile, so we call release() to avoid double deletion.
329 PreprocessorOpts.addRemappedFile(MainFilePath,
330 PreambleInputBuffer.release());
331 }
332
333 std::unique_ptr<PrecompilePreambleAction> Act;
Ilya Biryukov417085a2017-11-16 16:25:01 +0000334 Act.reset(new PrecompilePreambleAction(
335 StoreInMemory ? &Storage.asMemory().Data : nullptr, Callbacks));
Ilya Biryukov1f8647d2017-12-20 16:48:56 +0000336 Callbacks.BeforeExecute(*Clang);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000337 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
338 return BuildPreambleError::BeginSourceFileFailed;
339
Ilya Biryukov41e90bc2017-12-15 11:27:51 +0000340 std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
341 Callbacks.createPPCallbacks();
342 if (DelegatedPPCallbacks)
343 Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
344
Ilya Biryukov200b3282017-06-21 10:24:58 +0000345 Act->Execute();
346
347 // Run the callbacks.
348 Callbacks.AfterExecute(*Clang);
349
350 Act->EndSourceFile();
351
352 if (!Act->hasEmittedPreamblePCH())
353 return BuildPreambleError::CouldntEmitPCH;
354
355 // Keep track of all of the files that the source manager knows about,
356 // so we can verify whether they have changed or not.
357 llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
358
359 SourceManager &SourceMgr = Clang->getSourceManager();
360 for (auto &Filename : PreambleDepCollector->getDependencies()) {
361 const FileEntry *File = Clang->getFileManager().getFile(Filename);
362 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
363 continue;
364 if (time_t ModTime = File->getModificationTime()) {
365 FilesInPreamble[File->getName()] =
366 PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
367 ModTime);
368 } else {
369 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
370 FilesInPreamble[File->getName()] =
371 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
372 }
373 }
374
Ilya Biryukov417085a2017-11-16 16:25:01 +0000375 return PrecompiledPreamble(std::move(Storage), std::move(PreambleBytes),
376 PreambleEndsAtStartOfLine,
377 std::move(FilesInPreamble));
Ilya Biryukov200b3282017-06-21 10:24:58 +0000378}
379
380PreambleBounds PrecompiledPreamble::getBounds() const {
381 return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
382}
383
384bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation,
385 const llvm::MemoryBuffer *MainFileBuffer,
386 PreambleBounds Bounds,
387 vfs::FileSystem *VFS) const {
388
389 assert(
390 Bounds.Size <= MainFileBuffer->getBufferSize() &&
391 "Buffer is too large. Bounds were calculated from a different buffer?");
392
393 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
394 PreprocessorOptions &PreprocessorOpts =
395 PreambleInvocation->getPreprocessorOpts();
396
397 if (!Bounds.Size)
398 return false;
399
400 // We've previously computed a preamble. Check whether we have the same
401 // preamble now that we did before, and that there's enough space in
402 // the main-file buffer within the precompiled preamble to fit the
403 // new main file.
404 if (PreambleBytes.size() != Bounds.Size ||
405 PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
406 memcmp(PreambleBytes.data(), MainFileBuffer->getBufferStart(),
407 Bounds.Size) != 0)
408 return false;
409 // The preamble has not changed. We may be able to re-use the precompiled
410 // preamble.
411
412 // Check that none of the files used by the preamble have changed.
413 // First, make a record of those files that have been overridden via
414 // remapping or unsaved_files.
415 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
416 for (const auto &R : PreprocessorOpts.RemappedFiles) {
417 vfs::Status Status;
418 if (!moveOnNoError(VFS->status(R.second), Status)) {
419 // If we can't stat the file we're remapping to, assume that something
420 // horrible happened.
421 return false;
422 }
423
424 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
425 Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
426 }
427
428 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
429 vfs::Status Status;
430 if (!moveOnNoError(VFS->status(RB.first), Status))
431 return false;
432
433 OverriddenFiles[Status.getUniqueID()] =
434 PreambleFileHash::createForMemoryBuffer(RB.second);
435 }
436
437 // Check whether anything has changed.
438 for (const auto &F : FilesInPreamble) {
439 vfs::Status Status;
440 if (!moveOnNoError(VFS->status(F.first()), Status)) {
441 // If we can't stat the file, assume that something horrible happened.
442 return false;
443 }
444
445 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
446 OverriddenFiles.find(Status.getUniqueID());
447 if (Overridden != OverriddenFiles.end()) {
448 // This file was remapped; check whether the newly-mapped file
449 // matches up with the previous mapping.
450 if (Overridden->second != F.second)
451 return false;
452 continue;
453 }
454
455 // The file was not remapped; check whether it has changed on disk.
456 if (Status.getSize() != uint64_t(F.second.Size) ||
457 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
458 F.second.ModTime)
459 return false;
460 }
461 return true;
462}
463
464void PrecompiledPreamble::AddImplicitPreamble(
Ilya Biryukov417085a2017-11-16 16:25:01 +0000465 CompilerInvocation &CI, IntrusiveRefCntPtr<vfs::FileSystem> &VFS,
466 llvm::MemoryBuffer *MainFileBuffer) const {
467 assert(VFS && "VFS must not be null");
Ilya Biryukov200b3282017-06-21 10:24:58 +0000468
Ilya Biryukov417085a2017-11-16 16:25:01 +0000469 auto &PreprocessorOpts = CI.getPreprocessorOpts();
Ilya Biryukov200b3282017-06-21 10:24:58 +0000470
471 // Remap main file to point to MainFileBuffer.
472 auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
473 PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
Ilya Biryukov417085a2017-11-16 16:25:01 +0000474
475 // Configure ImpicitPCHInclude.
476 PreprocessorOpts.PrecompiledPreambleBytes.first = PreambleBytes.size();
477 PreprocessorOpts.PrecompiledPreambleBytes.second = PreambleEndsAtStartOfLine;
478 PreprocessorOpts.DisablePCHValidation = true;
479
480 setupPreambleStorage(Storage, PreprocessorOpts, VFS);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000481}
482
483PrecompiledPreamble::PrecompiledPreamble(
Ilya Biryukov417085a2017-11-16 16:25:01 +0000484 PCHStorage Storage, std::vector<char> PreambleBytes,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000485 bool PreambleEndsAtStartOfLine,
486 llvm::StringMap<PreambleFileHash> FilesInPreamble)
Ilya Biryukov417085a2017-11-16 16:25:01 +0000487 : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
Ilya Biryukov200b3282017-06-21 10:24:58 +0000488 PreambleBytes(std::move(PreambleBytes)),
Ilya Biryukov417085a2017-11-16 16:25:01 +0000489 PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
490 assert(this->Storage.getKind() != PCHStorage::Kind::Empty);
491}
Ilya Biryukov200b3282017-06-21 10:24:58 +0000492
493llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
494PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile() {
495 // FIXME: This is a hack so that we can override the preamble file during
496 // crash-recovery testing, which is the only case where the preamble files
497 // are not necessarily cleaned up.
498 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
499 if (TmpFile)
500 return TempPCHFile::createFromCustomPath(TmpFile);
501 return TempPCHFile::createInSystemTempDir("preamble", "pch");
502}
503
504llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
505PrecompiledPreamble::TempPCHFile::createInSystemTempDir(const Twine &Prefix,
506 StringRef Suffix) {
507 llvm::SmallString<64> File;
Ilya Biryukovb88de412017-08-10 16:10:40 +0000508 // Using a version of createTemporaryFile with a file descriptor guarantees
509 // that we would never get a race condition in a multi-threaded setting (i.e.,
510 // multiple threads getting the same temporary path).
511 int FD;
Ilya Biryukov417085a2017-11-16 16:25:01 +0000512 auto EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, FD, File);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000513 if (EC)
514 return EC;
Ilya Biryukovb88de412017-08-10 16:10:40 +0000515 // We only needed to make sure the file exists, close the file right away.
516 llvm::sys::Process::SafelyCloseFileDescriptor(FD);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000517 return TempPCHFile(std::move(File).str());
518}
519
520llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
521PrecompiledPreamble::TempPCHFile::createFromCustomPath(const Twine &Path) {
522 return TempPCHFile(Path.str());
523}
524
525PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath)
526 : FilePath(std::move(FilePath)) {
527 TemporaryFiles::getInstance().addFile(*this->FilePath);
528}
529
530PrecompiledPreamble::TempPCHFile::TempPCHFile(TempPCHFile &&Other) {
531 FilePath = std::move(Other.FilePath);
532 Other.FilePath = None;
533}
534
535PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::TempPCHFile::
536operator=(TempPCHFile &&Other) {
537 RemoveFileIfPresent();
538
539 FilePath = std::move(Other.FilePath);
540 Other.FilePath = None;
541 return *this;
542}
543
544PrecompiledPreamble::TempPCHFile::~TempPCHFile() { RemoveFileIfPresent(); }
545
546void PrecompiledPreamble::TempPCHFile::RemoveFileIfPresent() {
547 if (FilePath) {
548 TemporaryFiles::getInstance().removeFile(*FilePath);
549 FilePath = None;
550 }
551}
552
553llvm::StringRef PrecompiledPreamble::TempPCHFile::getFilePath() const {
554 assert(FilePath && "TempPCHFile doesn't have a FilePath. Had it been moved?");
555 return *FilePath;
556}
557
Ilya Biryukov417085a2017-11-16 16:25:01 +0000558PrecompiledPreamble::PCHStorage::PCHStorage(TempPCHFile File)
559 : StorageKind(Kind::TempFile) {
560 new (&asFile()) TempPCHFile(std::move(File));
561}
562
563PrecompiledPreamble::PCHStorage::PCHStorage(InMemoryPreamble Memory)
564 : StorageKind(Kind::InMemory) {
565 new (&asMemory()) InMemoryPreamble(std::move(Memory));
566}
567
568PrecompiledPreamble::PCHStorage::PCHStorage(PCHStorage &&Other) : PCHStorage() {
569 *this = std::move(Other);
570}
571
572PrecompiledPreamble::PCHStorage &PrecompiledPreamble::PCHStorage::
573operator=(PCHStorage &&Other) {
574 destroy();
575
576 StorageKind = Other.StorageKind;
577 switch (StorageKind) {
578 case Kind::Empty:
579 // do nothing;
580 break;
581 case Kind::TempFile:
582 new (&asFile()) TempPCHFile(std::move(Other.asFile()));
583 break;
584 case Kind::InMemory:
585 new (&asMemory()) InMemoryPreamble(std::move(Other.asMemory()));
586 break;
587 }
588
589 Other.setEmpty();
590 return *this;
591}
592
593PrecompiledPreamble::PCHStorage::~PCHStorage() { destroy(); }
594
595PrecompiledPreamble::PCHStorage::Kind
596PrecompiledPreamble::PCHStorage::getKind() const {
597 return StorageKind;
598}
599
600PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::PCHStorage::asFile() {
601 assert(getKind() == Kind::TempFile);
602 return *reinterpret_cast<TempPCHFile *>(Storage.buffer);
603}
604
605const PrecompiledPreamble::TempPCHFile &
606PrecompiledPreamble::PCHStorage::asFile() const {
607 return const_cast<PCHStorage *>(this)->asFile();
608}
609
610PrecompiledPreamble::InMemoryPreamble &
611PrecompiledPreamble::PCHStorage::asMemory() {
612 assert(getKind() == Kind::InMemory);
613 return *reinterpret_cast<InMemoryPreamble *>(Storage.buffer);
614}
615
616const PrecompiledPreamble::InMemoryPreamble &
617PrecompiledPreamble::PCHStorage::asMemory() const {
618 return const_cast<PCHStorage *>(this)->asMemory();
619}
620
621void PrecompiledPreamble::PCHStorage::destroy() {
622 switch (StorageKind) {
623 case Kind::Empty:
624 return;
625 case Kind::TempFile:
626 asFile().~TempPCHFile();
627 return;
628 case Kind::InMemory:
629 asMemory().~InMemoryPreamble();
630 return;
631 }
632}
633
634void PrecompiledPreamble::PCHStorage::setEmpty() {
635 destroy();
636 StorageKind = Kind::Empty;
637}
638
Ilya Biryukov200b3282017-06-21 10:24:58 +0000639PrecompiledPreamble::PreambleFileHash
640PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
641 time_t ModTime) {
642 PreambleFileHash Result;
643 Result.Size = Size;
644 Result.ModTime = ModTime;
645 Result.MD5 = {};
646 return Result;
647}
648
649PrecompiledPreamble::PreambleFileHash
650PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
651 const llvm::MemoryBuffer *Buffer) {
652 PreambleFileHash Result;
653 Result.Size = Buffer->getBufferSize();
654 Result.ModTime = 0;
655
656 llvm::MD5 MD5Ctx;
657 MD5Ctx.update(Buffer->getBuffer().data());
658 MD5Ctx.final(Result.MD5);
659
660 return Result;
661}
662
Ilya Biryukov417085a2017-11-16 16:25:01 +0000663void PrecompiledPreamble::setupPreambleStorage(
664 const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
665 IntrusiveRefCntPtr<vfs::FileSystem> &VFS) {
666 if (Storage.getKind() == PCHStorage::Kind::TempFile) {
667 const TempPCHFile &PCHFile = Storage.asFile();
668 PreprocessorOpts.ImplicitPCHInclude = PCHFile.getFilePath();
669
670 // Make sure we can access the PCH file even if we're using a VFS
671 IntrusiveRefCntPtr<vfs::FileSystem> RealFS = vfs::getRealFileSystem();
672 auto PCHPath = PCHFile.getFilePath();
673 if (VFS == RealFS || VFS->exists(PCHPath))
674 return;
675 auto Buf = RealFS->getBufferForFile(PCHPath);
676 if (!Buf) {
677 // We can't read the file even from RealFS, this is clearly an error,
678 // but we'll just leave the current VFS as is and let clang's code
679 // figure out what to do with missing PCH.
680 return;
681 }
682
683 // We have a slight inconsistency here -- we're using the VFS to
684 // read files, but the PCH was generated in the real file system.
685 VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
686 } else {
687 assert(Storage.getKind() == PCHStorage::Kind::InMemory);
688 // For in-memory preamble, we have to provide a VFS overlay that makes it
689 // accessible.
690 StringRef PCHPath = getInMemoryPreamblePath();
691 PreprocessorOpts.ImplicitPCHInclude = PCHPath;
692
Ilya Biryukov8318f61b2017-11-24 13:12:38 +0000693 auto Buf = llvm::MemoryBuffer::getMemBuffer(Storage.asMemory().Data);
Ilya Biryukov417085a2017-11-16 16:25:01 +0000694 VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
695 }
696}
697
Ilya Biryukov1f8647d2017-12-20 16:48:56 +0000698void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
Ilya Biryukov200b3282017-06-21 10:24:58 +0000699void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
700void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
701void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
Ilya Biryukov41e90bc2017-12-15 11:27:51 +0000702std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
703 return nullptr;
704}
Ilya Biryukov200b3282017-06-21 10:24:58 +0000705
706std::error_code clang::make_error_code(BuildPreambleError Error) {
707 return std::error_code(static_cast<int>(Error), BuildPreambleErrorCategory());
708}
709
710const char *BuildPreambleErrorCategory::name() const noexcept {
711 return "build-preamble.error";
712}
713
714std::string BuildPreambleErrorCategory::message(int condition) const {
715 switch (static_cast<BuildPreambleError>(condition)) {
716 case BuildPreambleError::PreambleIsEmpty:
717 return "Preamble is empty";
718 case BuildPreambleError::CouldntCreateTempFile:
719 return "Could not create temporary file for PCH";
720 case BuildPreambleError::CouldntCreateTargetInfo:
721 return "CreateTargetInfo() return null";
722 case BuildPreambleError::CouldntCreateVFSOverlay:
723 return "Could not create VFS Overlay";
724 case BuildPreambleError::BeginSourceFileFailed:
725 return "BeginSourceFile() return an error";
726 case BuildPreambleError::CouldntEmitPCH:
727 return "Could not emit PCH";
728 }
729 llvm_unreachable("unexpected BuildPreambleError");
730}