1 //===--- 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" 27 #include "llvm/Support/CrashRecoveryContext.h" 28 #include "llvm/Support/FileSystem.h" 29 #include "llvm/Support/Mutex.h" 30 #include "llvm/Support/MutexGuard.h" 31 #include "llvm/Support/Process.h" 32 33 using namespace clang; 34 35 namespace { 36 37 /// Keeps a track of files to be deleted in destructor. 38 class TemporaryFiles { 39 public: 40 // A static instance to be used by all clients. 41 static TemporaryFiles &getInstance(); 42 43 private: 44 // Disallow constructing the class directly. 45 TemporaryFiles() = default; 46 // Disallow copy. 47 TemporaryFiles(const TemporaryFiles &) = delete; 48 49 public: 50 ~TemporaryFiles(); 51 52 /// Adds \p File to a set of tracked files. 53 void addFile(StringRef File); 54 55 /// Remove \p File from disk and from the set of tracked files. 56 void removeFile(StringRef File); 57 58 private: 59 llvm::sys::SmartMutex<false> Mutex; 60 llvm::StringSet<> Files; 61 }; 62 63 TemporaryFiles &TemporaryFiles::getInstance() { 64 static TemporaryFiles Instance; 65 return Instance; 66 } 67 68 TemporaryFiles::~TemporaryFiles() { 69 llvm::MutexGuard Guard(Mutex); 70 for (const auto &File : Files) 71 llvm::sys::fs::remove(File.getKey()); 72 } 73 74 void TemporaryFiles::addFile(StringRef File) { 75 llvm::MutexGuard Guard(Mutex); 76 auto IsInserted = Files.insert(File).second; 77 (void)IsInserted; 78 assert(IsInserted && "File has already been added"); 79 } 80 81 void TemporaryFiles::removeFile(StringRef File) { 82 llvm::MutexGuard Guard(Mutex); 83 auto WasPresent = Files.erase(File); 84 (void)WasPresent; 85 assert(WasPresent && "File was not tracked"); 86 llvm::sys::fs::remove(File); 87 } 88 89 class PreambleMacroCallbacks : public PPCallbacks { 90 public: 91 PreambleMacroCallbacks(PreambleCallbacks &Callbacks) : Callbacks(Callbacks) {} 92 93 void MacroDefined(const Token &MacroNameTok, 94 const MacroDirective *MD) override { 95 Callbacks.HandleMacroDefined(MacroNameTok, MD); 96 } 97 98 private: 99 PreambleCallbacks &Callbacks; 100 }; 101 102 class PrecompilePreambleAction : public ASTFrontendAction { 103 public: 104 PrecompilePreambleAction(PreambleCallbacks &Callbacks) 105 : Callbacks(Callbacks) {} 106 107 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, 108 StringRef InFile) override; 109 110 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; } 111 112 void setEmittedPreamblePCH(ASTWriter &Writer) { 113 this->HasEmittedPreamblePCH = true; 114 Callbacks.AfterPCHEmitted(Writer); 115 } 116 117 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); } 118 bool hasCodeCompletionSupport() const override { return false; } 119 bool hasASTFileSupport() const override { return false; } 120 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; } 121 122 private: 123 friend class PrecompilePreambleConsumer; 124 125 bool HasEmittedPreamblePCH = false; 126 PreambleCallbacks &Callbacks; 127 }; 128 129 class PrecompilePreambleConsumer : public PCHGenerator { 130 public: 131 PrecompilePreambleConsumer(PrecompilePreambleAction &Action, 132 const Preprocessor &PP, StringRef isysroot, 133 std::unique_ptr<raw_ostream> Out) 134 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(), 135 ArrayRef<std::shared_ptr<ModuleFileExtension>>(), 136 /*AllowASTWithErrors=*/true), 137 Action(Action), Out(std::move(Out)) {} 138 139 bool HandleTopLevelDecl(DeclGroupRef DG) override { 140 Action.Callbacks.HandleTopLevelDecl(DG); 141 return true; 142 } 143 144 void HandleTranslationUnit(ASTContext &Ctx) override { 145 PCHGenerator::HandleTranslationUnit(Ctx); 146 if (!hasEmittedPCH()) 147 return; 148 149 // Write the generated bitstream to "Out". 150 *Out << getPCH(); 151 // Make sure it hits disk now. 152 Out->flush(); 153 // Free the buffer. 154 llvm::SmallVector<char, 0> Empty; 155 getPCH() = std::move(Empty); 156 157 Action.setEmittedPreamblePCH(getWriter()); 158 } 159 160 private: 161 PrecompilePreambleAction &Action; 162 std::unique_ptr<raw_ostream> Out; 163 }; 164 165 std::unique_ptr<ASTConsumer> 166 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI, 167 168 StringRef InFile) { 169 std::string Sysroot; 170 std::string OutputFile; 171 std::unique_ptr<raw_ostream> OS = 172 GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot, 173 OutputFile); 174 if (!OS) 175 return nullptr; 176 177 if (!CI.getFrontendOpts().RelocatablePCH) 178 Sysroot.clear(); 179 180 CI.getPreprocessor().addPPCallbacks( 181 llvm::make_unique<PreambleMacroCallbacks>(Callbacks)); 182 return llvm::make_unique<PrecompilePreambleConsumer>( 183 *this, CI.getPreprocessor(), Sysroot, std::move(OS)); 184 } 185 186 template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) { 187 if (!Val) 188 return false; 189 Output = std::move(*Val); 190 return true; 191 } 192 193 } // namespace 194 195 PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts, 196 llvm::MemoryBuffer *Buffer, 197 unsigned MaxLines) { 198 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(), LangOpts, MaxLines); 199 return PreambleBounds(Pre.first, Pre.second); 200 } 201 202 llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build( 203 const CompilerInvocation &Invocation, 204 const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, 205 DiagnosticsEngine &Diagnostics, IntrusiveRefCntPtr<vfs::FileSystem> VFS, 206 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 207 PreambleCallbacks &Callbacks) { 208 assert(VFS && "VFS is null"); 209 210 if (!Bounds.Size) 211 return BuildPreambleError::PreambleIsEmpty; 212 213 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation); 214 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts(); 215 PreprocessorOptions &PreprocessorOpts = 216 PreambleInvocation->getPreprocessorOpts(); 217 218 // Create a temporary file for the precompiled preamble. In rare 219 // circumstances, this can fail. 220 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> PreamblePCHFile = 221 PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile(); 222 if (!PreamblePCHFile) 223 return BuildPreambleError::CouldntCreateTempFile; 224 225 // Save the preamble text for later; we'll need to compare against it for 226 // subsequent reparses. 227 std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(), 228 MainFileBuffer->getBufferStart() + 229 Bounds.Size); 230 bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine; 231 232 // Tell the compiler invocation to generate a temporary precompiled header. 233 FrontendOpts.ProgramAction = frontend::GeneratePCH; 234 // FIXME: Generate the precompiled header into memory? 235 FrontendOpts.OutputFile = PreamblePCHFile->getFilePath(); 236 PreprocessorOpts.PrecompiledPreambleBytes.first = 0; 237 PreprocessorOpts.PrecompiledPreambleBytes.second = false; 238 239 // Create the compiler instance to use for building the precompiled preamble. 240 std::unique_ptr<CompilerInstance> Clang( 241 new CompilerInstance(std::move(PCHContainerOps))); 242 243 // Recover resources if we crash before exiting this method. 244 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup( 245 Clang.get()); 246 247 Clang->setInvocation(std::move(PreambleInvocation)); 248 Clang->setDiagnostics(&Diagnostics); 249 250 // Create the target instance. 251 Clang->setTarget(TargetInfo::CreateTargetInfo( 252 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts)); 253 if (!Clang->hasTarget()) 254 return BuildPreambleError::CouldntCreateTargetInfo; 255 256 // Inform the target of the language options. 257 // 258 // FIXME: We shouldn't need to do this, the target should be immutable once 259 // created. This complexity should be lifted elsewhere. 260 Clang->getTarget().adjust(Clang->getLangOpts()); 261 262 assert(Clang->getFrontendOpts().Inputs.size() == 1 && 263 "Invocation must have exactly one source file!"); 264 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() == 265 InputKind::Source && 266 "FIXME: AST inputs not yet supported here!"); 267 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() != 268 InputKind::LLVM_IR && 269 "IR inputs not support here!"); 270 271 // Clear out old caches and data. 272 Diagnostics.Reset(); 273 ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts()); 274 275 VFS = 276 createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS); 277 if (!VFS) 278 return BuildPreambleError::CouldntCreateVFSOverlay; 279 280 // Create a file manager object to provide access to and cache the filesystem. 281 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS)); 282 283 // Create the source manager. 284 Clang->setSourceManager( 285 new SourceManager(Diagnostics, Clang->getFileManager())); 286 287 auto PreambleDepCollector = std::make_shared<DependencyCollector>(); 288 Clang->addDependencyCollector(PreambleDepCollector); 289 290 // Remap the main source file to the preamble buffer. 291 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile(); 292 auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy( 293 MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath); 294 if (PreprocessorOpts.RetainRemappedFileBuffers) { 295 // MainFileBuffer will be deleted by unique_ptr after leaving the method. 296 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get()); 297 } else { 298 // In that case, remapped buffer will be deleted by CompilerInstance on 299 // BeginSourceFile, so we call release() to avoid double deletion. 300 PreprocessorOpts.addRemappedFile(MainFilePath, 301 PreambleInputBuffer.release()); 302 } 303 304 std::unique_ptr<PrecompilePreambleAction> Act; 305 Act.reset(new PrecompilePreambleAction(Callbacks)); 306 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) 307 return BuildPreambleError::BeginSourceFileFailed; 308 309 Act->Execute(); 310 311 // Run the callbacks. 312 Callbacks.AfterExecute(*Clang); 313 314 Act->EndSourceFile(); 315 316 if (!Act->hasEmittedPreamblePCH()) 317 return BuildPreambleError::CouldntEmitPCH; 318 319 // Keep track of all of the files that the source manager knows about, 320 // so we can verify whether they have changed or not. 321 llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble; 322 323 SourceManager &SourceMgr = Clang->getSourceManager(); 324 for (auto &Filename : PreambleDepCollector->getDependencies()) { 325 const FileEntry *File = Clang->getFileManager().getFile(Filename); 326 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())) 327 continue; 328 if (time_t ModTime = File->getModificationTime()) { 329 FilesInPreamble[File->getName()] = 330 PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(), 331 ModTime); 332 } else { 333 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File); 334 FilesInPreamble[File->getName()] = 335 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer); 336 } 337 } 338 339 return PrecompiledPreamble( 340 std::move(*PreamblePCHFile), std::move(PreambleBytes), 341 PreambleEndsAtStartOfLine, std::move(FilesInPreamble)); 342 } 343 344 PreambleBounds PrecompiledPreamble::getBounds() const { 345 return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine); 346 } 347 348 bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation, 349 const llvm::MemoryBuffer *MainFileBuffer, 350 PreambleBounds Bounds, 351 vfs::FileSystem *VFS) const { 352 353 assert( 354 Bounds.Size <= MainFileBuffer->getBufferSize() && 355 "Buffer is too large. Bounds were calculated from a different buffer?"); 356 357 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation); 358 PreprocessorOptions &PreprocessorOpts = 359 PreambleInvocation->getPreprocessorOpts(); 360 361 if (!Bounds.Size) 362 return false; 363 364 // We've previously computed a preamble. Check whether we have the same 365 // preamble now that we did before, and that there's enough space in 366 // the main-file buffer within the precompiled preamble to fit the 367 // new main file. 368 if (PreambleBytes.size() != Bounds.Size || 369 PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine || 370 memcmp(PreambleBytes.data(), MainFileBuffer->getBufferStart(), 371 Bounds.Size) != 0) 372 return false; 373 // The preamble has not changed. We may be able to re-use the precompiled 374 // preamble. 375 376 // Check that none of the files used by the preamble have changed. 377 // First, make a record of those files that have been overridden via 378 // remapping or unsaved_files. 379 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles; 380 for (const auto &R : PreprocessorOpts.RemappedFiles) { 381 vfs::Status Status; 382 if (!moveOnNoError(VFS->status(R.second), Status)) { 383 // If we can't stat the file we're remapping to, assume that something 384 // horrible happened. 385 return false; 386 } 387 388 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile( 389 Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime())); 390 } 391 392 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) { 393 vfs::Status Status; 394 if (!moveOnNoError(VFS->status(RB.first), Status)) 395 return false; 396 397 OverriddenFiles[Status.getUniqueID()] = 398 PreambleFileHash::createForMemoryBuffer(RB.second); 399 } 400 401 // Check whether anything has changed. 402 for (const auto &F : FilesInPreamble) { 403 vfs::Status Status; 404 if (!moveOnNoError(VFS->status(F.first()), Status)) { 405 // If we can't stat the file, assume that something horrible happened. 406 return false; 407 } 408 409 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden = 410 OverriddenFiles.find(Status.getUniqueID()); 411 if (Overridden != OverriddenFiles.end()) { 412 // This file was remapped; check whether the newly-mapped file 413 // matches up with the previous mapping. 414 if (Overridden->second != F.second) 415 return false; 416 continue; 417 } 418 419 // The file was not remapped; check whether it has changed on disk. 420 if (Status.getSize() != uint64_t(F.second.Size) || 421 llvm::sys::toTimeT(Status.getLastModificationTime()) != 422 F.second.ModTime) 423 return false; 424 } 425 return true; 426 } 427 428 void PrecompiledPreamble::AddImplicitPreamble( 429 CompilerInvocation &CI, llvm::MemoryBuffer *MainFileBuffer) const { 430 auto &PreprocessorOpts = CI.getPreprocessorOpts(); 431 432 // Configure ImpicitPCHInclude. 433 PreprocessorOpts.PrecompiledPreambleBytes.first = PreambleBytes.size(); 434 PreprocessorOpts.PrecompiledPreambleBytes.second = PreambleEndsAtStartOfLine; 435 PreprocessorOpts.ImplicitPCHInclude = PCHFile.getFilePath(); 436 PreprocessorOpts.DisablePCHValidation = true; 437 438 // Remap main file to point to MainFileBuffer. 439 auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile(); 440 PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer); 441 } 442 443 PrecompiledPreamble::PrecompiledPreamble( 444 TempPCHFile PCHFile, std::vector<char> PreambleBytes, 445 bool PreambleEndsAtStartOfLine, 446 llvm::StringMap<PreambleFileHash> FilesInPreamble) 447 : PCHFile(std::move(PCHFile)), FilesInPreamble(FilesInPreamble), 448 PreambleBytes(std::move(PreambleBytes)), 449 PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {} 450 451 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> 452 PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile() { 453 // FIXME: This is a hack so that we can override the preamble file during 454 // crash-recovery testing, which is the only case where the preamble files 455 // are not necessarily cleaned up. 456 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE"); 457 if (TmpFile) 458 return TempPCHFile::createFromCustomPath(TmpFile); 459 return TempPCHFile::createInSystemTempDir("preamble", "pch"); 460 } 461 462 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> 463 PrecompiledPreamble::TempPCHFile::createInSystemTempDir(const Twine &Prefix, 464 StringRef Suffix) { 465 llvm::SmallString<64> File; 466 // Using a version of createTemporaryFile with a file descriptor guarantees 467 // that we would never get a race condition in a multi-threaded setting (i.e., 468 // multiple threads getting the same temporary path). 469 int FD; 470 auto EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, /*ref*/ FD, 471 /*ref*/ File); 472 if (EC) 473 return EC; 474 // We only needed to make sure the file exists, close the file right away. 475 llvm::sys::Process::SafelyCloseFileDescriptor(FD); 476 return TempPCHFile(std::move(File).str()); 477 } 478 479 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> 480 PrecompiledPreamble::TempPCHFile::createFromCustomPath(const Twine &Path) { 481 return TempPCHFile(Path.str()); 482 } 483 484 PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath) 485 : FilePath(std::move(FilePath)) { 486 TemporaryFiles::getInstance().addFile(*this->FilePath); 487 } 488 489 PrecompiledPreamble::TempPCHFile::TempPCHFile(TempPCHFile &&Other) { 490 FilePath = std::move(Other.FilePath); 491 Other.FilePath = None; 492 } 493 494 PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::TempPCHFile:: 495 operator=(TempPCHFile &&Other) { 496 RemoveFileIfPresent(); 497 498 FilePath = std::move(Other.FilePath); 499 Other.FilePath = None; 500 return *this; 501 } 502 503 PrecompiledPreamble::TempPCHFile::~TempPCHFile() { RemoveFileIfPresent(); } 504 505 void PrecompiledPreamble::TempPCHFile::RemoveFileIfPresent() { 506 if (FilePath) { 507 TemporaryFiles::getInstance().removeFile(*FilePath); 508 FilePath = None; 509 } 510 } 511 512 llvm::StringRef PrecompiledPreamble::TempPCHFile::getFilePath() const { 513 assert(FilePath && "TempPCHFile doesn't have a FilePath. Had it been moved?"); 514 return *FilePath; 515 } 516 517 PrecompiledPreamble::PreambleFileHash 518 PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size, 519 time_t ModTime) { 520 PreambleFileHash Result; 521 Result.Size = Size; 522 Result.ModTime = ModTime; 523 Result.MD5 = {}; 524 return Result; 525 } 526 527 PrecompiledPreamble::PreambleFileHash 528 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer( 529 const llvm::MemoryBuffer *Buffer) { 530 PreambleFileHash Result; 531 Result.Size = Buffer->getBufferSize(); 532 Result.ModTime = 0; 533 534 llvm::MD5 MD5Ctx; 535 MD5Ctx.update(Buffer->getBuffer().data()); 536 MD5Ctx.final(Result.MD5); 537 538 return Result; 539 } 540 541 void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {} 542 void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {} 543 void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {} 544 void PreambleCallbacks::HandleMacroDefined(const Token &MacroNameTok, 545 const MacroDirective *MD) {} 546 547 std::error_code clang::make_error_code(BuildPreambleError Error) { 548 return std::error_code(static_cast<int>(Error), BuildPreambleErrorCategory()); 549 } 550 551 const char *BuildPreambleErrorCategory::name() const noexcept { 552 return "build-preamble.error"; 553 } 554 555 std::string BuildPreambleErrorCategory::message(int condition) const { 556 switch (static_cast<BuildPreambleError>(condition)) { 557 case BuildPreambleError::PreambleIsEmpty: 558 return "Preamble is empty"; 559 case BuildPreambleError::CouldntCreateTempFile: 560 return "Could not create temporary file for PCH"; 561 case BuildPreambleError::CouldntCreateTargetInfo: 562 return "CreateTargetInfo() return null"; 563 case BuildPreambleError::CouldntCreateVFSOverlay: 564 return "Could not create VFS Overlay"; 565 case BuildPreambleError::BeginSourceFileFailed: 566 return "BeginSourceFile() return an error"; 567 case BuildPreambleError::CouldntEmitPCH: 568 return "Could not emit PCH"; 569 } 570 llvm_unreachable("unexpected BuildPreambleError"); 571 } 572