1 //===- Tooling.cpp - Running clang standalone tools -----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements functions to run clang tools standalone instead 10 // of running them as a plugin. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Tooling/Tooling.h" 15 #include "clang/Basic/Diagnostic.h" 16 #include "clang/Basic/DiagnosticIDs.h" 17 #include "clang/Basic/DiagnosticOptions.h" 18 #include "clang/Basic/FileManager.h" 19 #include "clang/Basic/FileSystemOptions.h" 20 #include "clang/Basic/LLVM.h" 21 #include "clang/Driver/Compilation.h" 22 #include "clang/Driver/Driver.h" 23 #include "clang/Driver/Job.h" 24 #include "clang/Driver/Options.h" 25 #include "clang/Driver/Tool.h" 26 #include "clang/Driver/ToolChain.h" 27 #include "clang/Frontend/ASTUnit.h" 28 #include "clang/Frontend/CompilerInstance.h" 29 #include "clang/Frontend/CompilerInvocation.h" 30 #include "clang/Frontend/FrontendDiagnostic.h" 31 #include "clang/Frontend/FrontendOptions.h" 32 #include "clang/Frontend/TextDiagnosticPrinter.h" 33 #include "clang/Lex/HeaderSearchOptions.h" 34 #include "clang/Lex/PreprocessorOptions.h" 35 #include "clang/Tooling/ArgumentsAdjusters.h" 36 #include "clang/Tooling/CompilationDatabase.h" 37 #include "llvm/ADT/ArrayRef.h" 38 #include "llvm/ADT/IntrusiveRefCntPtr.h" 39 #include "llvm/ADT/SmallString.h" 40 #include "llvm/ADT/StringRef.h" 41 #include "llvm/ADT/Twine.h" 42 #include "llvm/Option/ArgList.h" 43 #include "llvm/Option/OptTable.h" 44 #include "llvm/Option/Option.h" 45 #include "llvm/Support/Casting.h" 46 #include "llvm/Support/Debug.h" 47 #include "llvm/Support/ErrorHandling.h" 48 #include "llvm/Support/FileSystem.h" 49 #include "llvm/Support/Host.h" 50 #include "llvm/Support/MemoryBuffer.h" 51 #include "llvm/Support/Path.h" 52 #include "llvm/Support/VirtualFileSystem.h" 53 #include "llvm/Support/raw_ostream.h" 54 #include <cassert> 55 #include <cstring> 56 #include <memory> 57 #include <string> 58 #include <system_error> 59 #include <utility> 60 #include <vector> 61 62 #define DEBUG_TYPE "clang-tooling" 63 64 using namespace clang; 65 using namespace tooling; 66 67 ToolAction::~ToolAction() = default; 68 69 FrontendActionFactory::~FrontendActionFactory() = default; 70 71 // FIXME: This file contains structural duplication with other parts of the 72 // code that sets up a compiler to run tools on it, and we should refactor 73 // it to be based on the same framework. 74 75 /// Builds a clang driver initialized for running clang tools. 76 static driver::Driver * 77 newDriver(DiagnosticsEngine *Diagnostics, const char *BinaryName, 78 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { 79 driver::Driver *CompilerDriver = 80 new driver::Driver(BinaryName, llvm::sys::getDefaultTargetTriple(), 81 *Diagnostics, std::move(VFS)); 82 CompilerDriver->setTitle("clang_based_tool"); 83 return CompilerDriver; 84 } 85 86 /// Retrieves the clang CC1 specific flags out of the compilation's jobs. 87 /// 88 /// Returns nullptr on error. 89 static const llvm::opt::ArgStringList *getCC1Arguments( 90 DiagnosticsEngine *Diagnostics, driver::Compilation *Compilation) { 91 // We expect to get back exactly one Command job, if we didn't something 92 // failed. Extract that job from the Compilation. 93 const driver::JobList &Jobs = Compilation->getJobs(); 94 if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) { 95 SmallString<256> error_msg; 96 llvm::raw_svector_ostream error_stream(error_msg); 97 Jobs.Print(error_stream, "; ", true); 98 Diagnostics->Report(diag::err_fe_expected_compiler_job) 99 << error_stream.str(); 100 return nullptr; 101 } 102 103 // The one job we find should be to invoke clang again. 104 const auto &Cmd = cast<driver::Command>(*Jobs.begin()); 105 if (StringRef(Cmd.getCreator().getName()) != "clang") { 106 Diagnostics->Report(diag::err_fe_expected_clang_command); 107 return nullptr; 108 } 109 110 return &Cmd.getArguments(); 111 } 112 113 namespace clang { 114 namespace tooling { 115 116 /// Returns a clang build invocation initialized from the CC1 flags. 117 CompilerInvocation *newInvocation( 118 DiagnosticsEngine *Diagnostics, const llvm::opt::ArgStringList &CC1Args) { 119 assert(!CC1Args.empty() && "Must at least contain the program name!"); 120 CompilerInvocation *Invocation = new CompilerInvocation; 121 CompilerInvocation::CreateFromArgs(*Invocation, CC1Args, *Diagnostics); 122 Invocation->getFrontendOpts().DisableFree = false; 123 Invocation->getCodeGenOpts().DisableFree = false; 124 return Invocation; 125 } 126 127 bool runToolOnCode(FrontendAction *ToolAction, const Twine &Code, 128 const Twine &FileName, 129 std::shared_ptr<PCHContainerOperations> PCHContainerOps) { 130 return runToolOnCodeWithArgs(ToolAction, Code, std::vector<std::string>(), 131 FileName, "clang-tool", 132 std::move(PCHContainerOps)); 133 } 134 135 } // namespace tooling 136 } // namespace clang 137 138 static std::vector<std::string> 139 getSyntaxOnlyToolArgs(const Twine &ToolName, 140 const std::vector<std::string> &ExtraArgs, 141 StringRef FileName) { 142 std::vector<std::string> Args; 143 Args.push_back(ToolName.str()); 144 Args.push_back("-fsyntax-only"); 145 Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end()); 146 Args.push_back(FileName.str()); 147 return Args; 148 } 149 150 namespace clang { 151 namespace tooling { 152 153 bool runToolOnCodeWithArgs( 154 FrontendAction *ToolAction, const Twine &Code, 155 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, 156 const std::vector<std::string> &Args, const Twine &FileName, 157 const Twine &ToolName, 158 std::shared_ptr<PCHContainerOperations> PCHContainerOps) { 159 SmallString<16> FileNameStorage; 160 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage); 161 162 llvm::IntrusiveRefCntPtr<FileManager> Files( 163 new FileManager(FileSystemOptions(), VFS)); 164 ArgumentsAdjuster Adjuster = getClangStripDependencyFileAdjuster(); 165 ToolInvocation Invocation( 166 getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef), 167 ToolAction, Files.get(), 168 std::move(PCHContainerOps)); 169 return Invocation.run(); 170 } 171 172 bool runToolOnCodeWithArgs( 173 FrontendAction *ToolAction, const Twine &Code, 174 const std::vector<std::string> &Args, const Twine &FileName, 175 const Twine &ToolName, 176 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 177 const FileContentMappings &VirtualMappedFiles) { 178 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem( 179 new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())); 180 llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( 181 new llvm::vfs::InMemoryFileSystem); 182 OverlayFileSystem->pushOverlay(InMemoryFileSystem); 183 184 SmallString<1024> CodeStorage; 185 InMemoryFileSystem->addFile(FileName, 0, 186 llvm::MemoryBuffer::getMemBuffer( 187 Code.toNullTerminatedStringRef(CodeStorage))); 188 189 for (auto &FilenameWithContent : VirtualMappedFiles) { 190 InMemoryFileSystem->addFile( 191 FilenameWithContent.first, 0, 192 llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second)); 193 } 194 195 return runToolOnCodeWithArgs(ToolAction, Code, OverlayFileSystem, Args, 196 FileName, ToolName); 197 } 198 199 llvm::Expected<std::string> getAbsolutePath(llvm::vfs::FileSystem &FS, 200 StringRef File) { 201 StringRef RelativePath(File); 202 // FIXME: Should '.\\' be accepted on Win32? 203 if (RelativePath.startswith("./")) { 204 RelativePath = RelativePath.substr(strlen("./")); 205 } 206 207 SmallString<1024> AbsolutePath = RelativePath; 208 if (auto EC = FS.makeAbsolute(AbsolutePath)) 209 return llvm::errorCodeToError(EC); 210 llvm::sys::path::native(AbsolutePath); 211 return AbsolutePath.str(); 212 } 213 214 std::string getAbsolutePath(StringRef File) { 215 return llvm::cantFail(getAbsolutePath(*llvm::vfs::getRealFileSystem(), File)); 216 } 217 218 void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine, 219 StringRef InvokedAs) { 220 if (!CommandLine.empty() && !InvokedAs.empty()) { 221 bool AlreadyHasTarget = false; 222 bool AlreadyHasMode = false; 223 // Skip CommandLine[0]. 224 for (auto Token = ++CommandLine.begin(); Token != CommandLine.end(); 225 ++Token) { 226 StringRef TokenRef(*Token); 227 AlreadyHasTarget |= 228 (TokenRef == "-target" || TokenRef.startswith("-target=")); 229 AlreadyHasMode |= (TokenRef == "--driver-mode" || 230 TokenRef.startswith("--driver-mode=")); 231 } 232 auto TargetMode = 233 driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs); 234 if (!AlreadyHasMode && TargetMode.DriverMode) { 235 CommandLine.insert(++CommandLine.begin(), TargetMode.DriverMode); 236 } 237 if (!AlreadyHasTarget && TargetMode.TargetIsValid) { 238 CommandLine.insert(++CommandLine.begin(), {"-target", 239 TargetMode.TargetPrefix}); 240 } 241 } 242 } 243 244 } // namespace tooling 245 } // namespace clang 246 247 namespace { 248 249 class SingleFrontendActionFactory : public FrontendActionFactory { 250 FrontendAction *Action; 251 252 public: 253 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {} 254 255 FrontendAction *create() override { return Action; } 256 }; 257 258 } // namespace 259 260 ToolInvocation::ToolInvocation( 261 std::vector<std::string> CommandLine, ToolAction *Action, 262 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps) 263 : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false), 264 Files(Files), PCHContainerOps(std::move(PCHContainerOps)) {} 265 266 ToolInvocation::ToolInvocation( 267 std::vector<std::string> CommandLine, FrontendAction *FAction, 268 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps) 269 : CommandLine(std::move(CommandLine)), 270 Action(new SingleFrontendActionFactory(FAction)), OwnsAction(true), 271 Files(Files), PCHContainerOps(std::move(PCHContainerOps)) {} 272 273 ToolInvocation::~ToolInvocation() { 274 if (OwnsAction) 275 delete Action; 276 } 277 278 void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) { 279 SmallString<1024> PathStorage; 280 llvm::sys::path::native(FilePath, PathStorage); 281 MappedFileContents[PathStorage] = Content; 282 } 283 284 bool ToolInvocation::run() { 285 std::vector<const char*> Argv; 286 for (const std::string &Str : CommandLine) 287 Argv.push_back(Str.c_str()); 288 const char *const BinaryName = Argv[0]; 289 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); 290 unsigned MissingArgIndex, MissingArgCount; 291 std::unique_ptr<llvm::opt::OptTable> Opts = driver::createDriverOptTable(); 292 llvm::opt::InputArgList ParsedArgs = Opts->ParseArgs( 293 ArrayRef<const char *>(Argv).slice(1), MissingArgIndex, MissingArgCount); 294 ParseDiagnosticArgs(*DiagOpts, ParsedArgs); 295 TextDiagnosticPrinter DiagnosticPrinter( 296 llvm::errs(), &*DiagOpts); 297 DiagnosticsEngine Diagnostics( 298 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, 299 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false); 300 301 const std::unique_ptr<driver::Driver> Driver( 302 newDriver(&Diagnostics, BinaryName, &Files->getVirtualFileSystem())); 303 // The "input file not found" diagnostics from the driver are useful. 304 // The driver is only aware of the VFS working directory, but some clients 305 // change this at the FileManager level instead. 306 // In this case the checks have false positives, so skip them. 307 if (!Files->getFileSystemOpts().WorkingDir.empty()) 308 Driver->setCheckInputsExist(false); 309 const std::unique_ptr<driver::Compilation> Compilation( 310 Driver->BuildCompilation(llvm::makeArrayRef(Argv))); 311 if (!Compilation) 312 return false; 313 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments( 314 &Diagnostics, Compilation.get()); 315 if (!CC1Args) 316 return false; 317 std::unique_ptr<CompilerInvocation> Invocation( 318 newInvocation(&Diagnostics, *CC1Args)); 319 // FIXME: remove this when all users have migrated! 320 for (const auto &It : MappedFileContents) { 321 // Inject the code as the given file name into the preprocessor options. 322 std::unique_ptr<llvm::MemoryBuffer> Input = 323 llvm::MemoryBuffer::getMemBuffer(It.getValue()); 324 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(), 325 Input.release()); 326 } 327 return runInvocation(BinaryName, Compilation.get(), std::move(Invocation), 328 std::move(PCHContainerOps)); 329 } 330 331 bool ToolInvocation::runInvocation( 332 const char *BinaryName, driver::Compilation *Compilation, 333 std::shared_ptr<CompilerInvocation> Invocation, 334 std::shared_ptr<PCHContainerOperations> PCHContainerOps) { 335 // Show the invocation, with -v. 336 if (Invocation->getHeaderSearchOpts().Verbose) { 337 llvm::errs() << "clang Invocation:\n"; 338 Compilation->getJobs().Print(llvm::errs(), "\n", true); 339 llvm::errs() << "\n"; 340 } 341 342 return Action->runInvocation(std::move(Invocation), Files, 343 std::move(PCHContainerOps), DiagConsumer); 344 } 345 346 bool FrontendActionFactory::runInvocation( 347 std::shared_ptr<CompilerInvocation> Invocation, FileManager *Files, 348 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 349 DiagnosticConsumer *DiagConsumer) { 350 // Create a compiler instance to handle the actual work. 351 CompilerInstance Compiler(std::move(PCHContainerOps)); 352 Compiler.setInvocation(std::move(Invocation)); 353 Compiler.setFileManager(Files); 354 355 // The FrontendAction can have lifetime requirements for Compiler or its 356 // members, and we need to ensure it's deleted earlier than Compiler. So we 357 // pass it to an std::unique_ptr declared after the Compiler variable. 358 std::unique_ptr<FrontendAction> ScopedToolAction(create()); 359 360 // Create the compiler's actual diagnostics engine. 361 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false); 362 if (!Compiler.hasDiagnostics()) 363 return false; 364 365 Compiler.createSourceManager(*Files); 366 367 const bool Success = Compiler.ExecuteAction(*ScopedToolAction); 368 369 Files->clearStatCache(); 370 return Success; 371 } 372 373 ClangTool::ClangTool(const CompilationDatabase &Compilations, 374 ArrayRef<std::string> SourcePaths, 375 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 376 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) 377 : Compilations(Compilations), SourcePaths(SourcePaths), 378 PCHContainerOps(std::move(PCHContainerOps)), 379 OverlayFileSystem(new llvm::vfs::OverlayFileSystem(std::move(BaseFS))), 380 InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem), 381 Files(new FileManager(FileSystemOptions(), OverlayFileSystem)) { 382 OverlayFileSystem->pushOverlay(InMemoryFileSystem); 383 appendArgumentsAdjuster(getClangStripOutputAdjuster()); 384 appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster()); 385 appendArgumentsAdjuster(getClangStripDependencyFileAdjuster()); 386 } 387 388 ClangTool::~ClangTool() = default; 389 390 void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) { 391 MappedFileContents.push_back(std::make_pair(FilePath, Content)); 392 } 393 394 void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) { 395 ArgsAdjuster = combineAdjusters(std::move(ArgsAdjuster), std::move(Adjuster)); 396 } 397 398 void ClangTool::clearArgumentsAdjusters() { 399 ArgsAdjuster = nullptr; 400 } 401 402 static void injectResourceDir(CommandLineArguments &Args, const char *Argv0, 403 void *MainAddr) { 404 // Allow users to override the resource dir. 405 for (StringRef Arg : Args) 406 if (Arg.startswith("-resource-dir")) 407 return; 408 409 // If there's no override in place add our resource dir. 410 Args.push_back("-resource-dir=" + 411 CompilerInvocation::GetResourcesPath(Argv0, MainAddr)); 412 } 413 414 int ClangTool::run(ToolAction *Action) { 415 // Exists solely for the purpose of lookup of the resource path. 416 // This just needs to be some symbol in the binary. 417 static int StaticSymbol; 418 419 // First insert all absolute paths into the in-memory VFS. These are global 420 // for all compile commands. 421 if (SeenWorkingDirectories.insert("/").second) 422 for (const auto &MappedFile : MappedFileContents) 423 if (llvm::sys::path::is_absolute(MappedFile.first)) 424 InMemoryFileSystem->addFile( 425 MappedFile.first, 0, 426 llvm::MemoryBuffer::getMemBuffer(MappedFile.second)); 427 428 bool ProcessingFailed = false; 429 bool FileSkipped = false; 430 // Compute all absolute paths before we run any actions, as those will change 431 // the working directory. 432 std::vector<std::string> AbsolutePaths; 433 AbsolutePaths.reserve(SourcePaths.size()); 434 for (const auto &SourcePath : SourcePaths) { 435 auto AbsPath = getAbsolutePath(*OverlayFileSystem, SourcePath); 436 if (!AbsPath) { 437 llvm::errs() << "Skipping " << SourcePath 438 << ". Error while getting an absolute path: " 439 << llvm::toString(AbsPath.takeError()) << "\n"; 440 continue; 441 } 442 AbsolutePaths.push_back(std::move(*AbsPath)); 443 } 444 445 // Remember the working directory in case we need to restore it. 446 std::string InitialWorkingDir; 447 if (RestoreCWD) { 448 if (auto CWD = OverlayFileSystem->getCurrentWorkingDirectory()) { 449 InitialWorkingDir = std::move(*CWD); 450 } else { 451 llvm::errs() << "Could not get working directory: " 452 << CWD.getError().message() << "\n"; 453 } 454 } 455 456 for (llvm::StringRef File : AbsolutePaths) { 457 // Currently implementations of CompilationDatabase::getCompileCommands can 458 // change the state of the file system (e.g. prepare generated headers), so 459 // this method needs to run right before we invoke the tool, as the next 460 // file may require a different (incompatible) state of the file system. 461 // 462 // FIXME: Make the compilation database interface more explicit about the 463 // requirements to the order of invocation of its members. 464 std::vector<CompileCommand> CompileCommandsForFile = 465 Compilations.getCompileCommands(File); 466 if (CompileCommandsForFile.empty()) { 467 llvm::errs() << "Skipping " << File << ". Compile command not found.\n"; 468 FileSkipped = true; 469 continue; 470 } 471 for (CompileCommand &CompileCommand : CompileCommandsForFile) { 472 // FIXME: chdir is thread hostile; on the other hand, creating the same 473 // behavior as chdir is complex: chdir resolves the path once, thus 474 // guaranteeing that all subsequent relative path operations work 475 // on the same path the original chdir resulted in. This makes a 476 // difference for example on network filesystems, where symlinks might be 477 // switched during runtime of the tool. Fixing this depends on having a 478 // file system abstraction that allows openat() style interactions. 479 if (OverlayFileSystem->setCurrentWorkingDirectory( 480 CompileCommand.Directory)) 481 llvm::report_fatal_error("Cannot chdir into \"" + 482 Twine(CompileCommand.Directory) + "\"!"); 483 484 // Now fill the in-memory VFS with the relative file mappings so it will 485 // have the correct relative paths. We never remove mappings but that 486 // should be fine. 487 if (SeenWorkingDirectories.insert(CompileCommand.Directory).second) 488 for (const auto &MappedFile : MappedFileContents) 489 if (!llvm::sys::path::is_absolute(MappedFile.first)) 490 InMemoryFileSystem->addFile( 491 MappedFile.first, 0, 492 llvm::MemoryBuffer::getMemBuffer(MappedFile.second)); 493 494 std::vector<std::string> CommandLine = CompileCommand.CommandLine; 495 if (ArgsAdjuster) 496 CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename); 497 assert(!CommandLine.empty()); 498 499 // Add the resource dir based on the binary of this tool. argv[0] in the 500 // compilation database may refer to a different compiler and we want to 501 // pick up the very same standard library that compiler is using. The 502 // builtin headers in the resource dir need to match the exact clang 503 // version the tool is using. 504 // FIXME: On linux, GetMainExecutable is independent of the value of the 505 // first argument, thus allowing ClangTool and runToolOnCode to just 506 // pass in made-up names here. Make sure this works on other platforms. 507 injectResourceDir(CommandLine, "clang_tool", &StaticSymbol); 508 509 // FIXME: We need a callback mechanism for the tool writer to output a 510 // customized message for each file. 511 LLVM_DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; }); 512 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(), 513 PCHContainerOps); 514 Invocation.setDiagnosticConsumer(DiagConsumer); 515 516 if (!Invocation.run()) { 517 // FIXME: Diagnostics should be used instead. 518 if (PrintErrorMessage) 519 llvm::errs() << "Error while processing " << File << ".\n"; 520 ProcessingFailed = true; 521 } 522 } 523 } 524 525 if (!InitialWorkingDir.empty()) { 526 if (auto EC = 527 OverlayFileSystem->setCurrentWorkingDirectory(InitialWorkingDir)) 528 llvm::errs() << "Error when trying to restore working dir: " 529 << EC.message() << "\n"; 530 } 531 return ProcessingFailed ? 1 : (FileSkipped ? 2 : 0); 532 } 533 534 namespace { 535 536 class ASTBuilderAction : public ToolAction { 537 std::vector<std::unique_ptr<ASTUnit>> &ASTs; 538 539 public: 540 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {} 541 542 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation, 543 FileManager *Files, 544 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 545 DiagnosticConsumer *DiagConsumer) override { 546 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation( 547 Invocation, std::move(PCHContainerOps), 548 CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(), 549 DiagConsumer, 550 /*ShouldOwnClient=*/false), 551 Files); 552 if (!AST) 553 return false; 554 555 ASTs.push_back(std::move(AST)); 556 return true; 557 } 558 }; 559 560 } // namespace 561 562 int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) { 563 ASTBuilderAction Action(ASTs); 564 return run(&Action); 565 } 566 567 void ClangTool::setRestoreWorkingDir(bool RestoreCWD) { 568 this->RestoreCWD = RestoreCWD; 569 } 570 571 void ClangTool::setPrintErrorMessage(bool PrintErrorMessage) { 572 this->PrintErrorMessage = PrintErrorMessage; 573 } 574 575 namespace clang { 576 namespace tooling { 577 578 std::unique_ptr<ASTUnit> 579 buildASTFromCode(StringRef Code, StringRef FileName, 580 std::shared_ptr<PCHContainerOperations> PCHContainerOps) { 581 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName, 582 "clang-tool", std::move(PCHContainerOps)); 583 } 584 585 std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs( 586 StringRef Code, const std::vector<std::string> &Args, StringRef FileName, 587 StringRef ToolName, std::shared_ptr<PCHContainerOperations> PCHContainerOps, 588 ArgumentsAdjuster Adjuster) { 589 std::vector<std::unique_ptr<ASTUnit>> ASTs; 590 ASTBuilderAction Action(ASTs); 591 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem( 592 new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())); 593 llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( 594 new llvm::vfs::InMemoryFileSystem); 595 OverlayFileSystem->pushOverlay(InMemoryFileSystem); 596 llvm::IntrusiveRefCntPtr<FileManager> Files( 597 new FileManager(FileSystemOptions(), OverlayFileSystem)); 598 599 ToolInvocation Invocation( 600 getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileName), FileName), 601 &Action, Files.get(), std::move(PCHContainerOps)); 602 603 InMemoryFileSystem->addFile(FileName, 0, 604 llvm::MemoryBuffer::getMemBufferCopy(Code)); 605 if (!Invocation.run()) 606 return nullptr; 607 608 assert(ASTs.size() == 1); 609 return std::move(ASTs[0]); 610 } 611 612 } // namespace tooling 613 } // namespace clang 614