1 //===--- Tooling.cpp - Running clang standalone tools ---------------------===// 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 // This file implements functions to run clang tools standalone instead 11 // of running them as a plugin. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Tooling/Tooling.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/Driver/Compilation.h" 18 #include "clang/Driver/Driver.h" 19 #include "clang/Driver/Tool.h" 20 #include "clang/Driver/ToolChain.h" 21 #include "clang/Frontend/ASTUnit.h" 22 #include "clang/Frontend/CompilerInstance.h" 23 #include "clang/Frontend/FrontendDiagnostic.h" 24 #include "clang/Frontend/TextDiagnosticPrinter.h" 25 #include "clang/Tooling/ArgumentsAdjusters.h" 26 #include "clang/Tooling/CompilationDatabase.h" 27 #include "llvm/ADT/STLExtras.h" 28 #include "llvm/Config/llvm-config.h" 29 #include "llvm/Option/Option.h" 30 #include "llvm/Support/Debug.h" 31 #include "llvm/Support/FileSystem.h" 32 #include "llvm/Support/Host.h" 33 #include "llvm/Support/raw_ostream.h" 34 35 #define DEBUG_TYPE "clang-tooling" 36 37 namespace clang { 38 namespace tooling { 39 40 ToolAction::~ToolAction() {} 41 42 FrontendActionFactory::~FrontendActionFactory() {} 43 44 // FIXME: This file contains structural duplication with other parts of the 45 // code that sets up a compiler to run tools on it, and we should refactor 46 // it to be based on the same framework. 47 48 /// \brief Builds a clang driver initialized for running clang tools. 49 static clang::driver::Driver *newDriver( 50 clang::DiagnosticsEngine *Diagnostics, const char *BinaryName, 51 IntrusiveRefCntPtr<vfs::FileSystem> VFS) { 52 clang::driver::Driver *CompilerDriver = new clang::driver::Driver( 53 BinaryName, llvm::sys::getDefaultTargetTriple(), *Diagnostics, VFS); 54 CompilerDriver->setTitle("clang_based_tool"); 55 return CompilerDriver; 56 } 57 58 /// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs. 59 /// 60 /// Returns NULL on error. 61 static const llvm::opt::ArgStringList *getCC1Arguments( 62 clang::DiagnosticsEngine *Diagnostics, 63 clang::driver::Compilation *Compilation) { 64 // We expect to get back exactly one Command job, if we didn't something 65 // failed. Extract that job from the Compilation. 66 const clang::driver::JobList &Jobs = Compilation->getJobs(); 67 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) { 68 SmallString<256> error_msg; 69 llvm::raw_svector_ostream error_stream(error_msg); 70 Jobs.Print(error_stream, "; ", true); 71 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job) 72 << error_stream.str(); 73 return nullptr; 74 } 75 76 // The one job we find should be to invoke clang again. 77 const clang::driver::Command &Cmd = 78 cast<clang::driver::Command>(*Jobs.begin()); 79 if (StringRef(Cmd.getCreator().getName()) != "clang") { 80 Diagnostics->Report(clang::diag::err_fe_expected_clang_command); 81 return nullptr; 82 } 83 84 return &Cmd.getArguments(); 85 } 86 87 /// \brief Returns a clang build invocation initialized from the CC1 flags. 88 clang::CompilerInvocation *newInvocation( 89 clang::DiagnosticsEngine *Diagnostics, 90 const llvm::opt::ArgStringList &CC1Args) { 91 assert(!CC1Args.empty() && "Must at least contain the program name!"); 92 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation; 93 clang::CompilerInvocation::CreateFromArgs( 94 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(), 95 *Diagnostics); 96 Invocation->getFrontendOpts().DisableFree = false; 97 Invocation->getCodeGenOpts().DisableFree = false; 98 Invocation->getDependencyOutputOpts() = DependencyOutputOptions(); 99 return Invocation; 100 } 101 102 bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code, 103 const Twine &FileName, 104 std::shared_ptr<PCHContainerOperations> PCHContainerOps) { 105 return runToolOnCodeWithArgs(ToolAction, Code, std::vector<std::string>(), 106 FileName, "clang-tool", PCHContainerOps); 107 } 108 109 static std::vector<std::string> 110 getSyntaxOnlyToolArgs(const Twine &ToolName, 111 const std::vector<std::string> &ExtraArgs, 112 StringRef FileName) { 113 std::vector<std::string> Args; 114 Args.push_back(ToolName.str()); 115 Args.push_back("-fsyntax-only"); 116 Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end()); 117 Args.push_back(FileName.str()); 118 return Args; 119 } 120 121 bool runToolOnCodeWithArgs( 122 clang::FrontendAction *ToolAction, const Twine &Code, 123 const std::vector<std::string> &Args, const Twine &FileName, 124 const Twine &ToolName, 125 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 126 const FileContentMappings &VirtualMappedFiles) { 127 128 SmallString<16> FileNameStorage; 129 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage); 130 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem( 131 new vfs::OverlayFileSystem(vfs::getRealFileSystem())); 132 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem( 133 new vfs::InMemoryFileSystem); 134 OverlayFileSystem->pushOverlay(InMemoryFileSystem); 135 llvm::IntrusiveRefCntPtr<FileManager> Files( 136 new FileManager(FileSystemOptions(), OverlayFileSystem)); 137 ToolInvocation Invocation(getSyntaxOnlyToolArgs(ToolName, Args, FileNameRef), 138 ToolAction, Files.get(), PCHContainerOps); 139 140 SmallString<1024> CodeStorage; 141 InMemoryFileSystem->addFile(FileNameRef, 0, 142 llvm::MemoryBuffer::getMemBuffer( 143 Code.toNullTerminatedStringRef(CodeStorage))); 144 145 for (auto &FilenameWithContent : VirtualMappedFiles) { 146 InMemoryFileSystem->addFile( 147 FilenameWithContent.first, 0, 148 llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second)); 149 } 150 151 return Invocation.run(); 152 } 153 154 std::string getAbsolutePath(StringRef File) { 155 StringRef RelativePath(File); 156 // FIXME: Should '.\\' be accepted on Win32? 157 if (RelativePath.startswith("./")) { 158 RelativePath = RelativePath.substr(strlen("./")); 159 } 160 161 SmallString<1024> AbsolutePath = RelativePath; 162 std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath); 163 assert(!EC); 164 (void)EC; 165 llvm::sys::path::native(AbsolutePath); 166 return AbsolutePath.str(); 167 } 168 169 void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine, 170 StringRef InvokedAs) { 171 if (!CommandLine.empty() && !InvokedAs.empty()) { 172 bool AlreadyHasTarget = false; 173 bool AlreadyHasMode = false; 174 // Skip CommandLine[0]. 175 for (auto Token = ++CommandLine.begin(); Token != CommandLine.end(); 176 ++Token) { 177 StringRef TokenRef(*Token); 178 AlreadyHasTarget |= 179 (TokenRef == "-target" || TokenRef.startswith("-target=")); 180 AlreadyHasMode |= (TokenRef == "--driver-mode" || 181 TokenRef.startswith("--driver-mode=")); 182 } 183 auto TargetMode = 184 clang::driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs); 185 if (!AlreadyHasMode && !TargetMode.second.empty()) { 186 CommandLine.insert(++CommandLine.begin(), TargetMode.second); 187 } 188 if (!AlreadyHasTarget && !TargetMode.first.empty()) { 189 CommandLine.insert(++CommandLine.begin(), {"-target", TargetMode.first}); 190 } 191 } 192 } 193 194 namespace { 195 196 class SingleFrontendActionFactory : public FrontendActionFactory { 197 FrontendAction *Action; 198 199 public: 200 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {} 201 202 FrontendAction *create() override { return Action; } 203 }; 204 205 } 206 207 ToolInvocation::ToolInvocation( 208 std::vector<std::string> CommandLine, ToolAction *Action, 209 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps) 210 : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false), 211 Files(Files), PCHContainerOps(PCHContainerOps), DiagConsumer(nullptr) {} 212 213 ToolInvocation::ToolInvocation( 214 std::vector<std::string> CommandLine, FrontendAction *FAction, 215 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps) 216 : CommandLine(std::move(CommandLine)), 217 Action(new SingleFrontendActionFactory(FAction)), OwnsAction(true), 218 Files(Files), PCHContainerOps(PCHContainerOps), DiagConsumer(nullptr) {} 219 220 ToolInvocation::~ToolInvocation() { 221 if (OwnsAction) 222 delete Action; 223 } 224 225 void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) { 226 SmallString<1024> PathStorage; 227 llvm::sys::path::native(FilePath, PathStorage); 228 MappedFileContents[PathStorage] = Content; 229 } 230 231 bool ToolInvocation::run() { 232 std::vector<const char*> Argv; 233 for (const std::string &Str : CommandLine) 234 Argv.push_back(Str.c_str()); 235 const char *const BinaryName = Argv[0]; 236 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); 237 TextDiagnosticPrinter DiagnosticPrinter( 238 llvm::errs(), &*DiagOpts); 239 DiagnosticsEngine Diagnostics( 240 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, 241 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false); 242 243 const std::unique_ptr<clang::driver::Driver> Driver( 244 newDriver(&Diagnostics, BinaryName, Files->getVirtualFileSystem())); 245 // Since the input might only be virtual, don't check whether it exists. 246 Driver->setCheckInputsExist(false); 247 const std::unique_ptr<clang::driver::Compilation> Compilation( 248 Driver->BuildCompilation(llvm::makeArrayRef(Argv))); 249 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments( 250 &Diagnostics, Compilation.get()); 251 if (!CC1Args) { 252 return false; 253 } 254 std::unique_ptr<clang::CompilerInvocation> Invocation( 255 newInvocation(&Diagnostics, *CC1Args)); 256 // FIXME: remove this when all users have migrated! 257 for (const auto &It : MappedFileContents) { 258 // Inject the code as the given file name into the preprocessor options. 259 std::unique_ptr<llvm::MemoryBuffer> Input = 260 llvm::MemoryBuffer::getMemBuffer(It.getValue()); 261 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(), 262 Input.release()); 263 } 264 return runInvocation(BinaryName, Compilation.get(), Invocation.release(), 265 PCHContainerOps); 266 } 267 268 bool ToolInvocation::runInvocation( 269 const char *BinaryName, clang::driver::Compilation *Compilation, 270 clang::CompilerInvocation *Invocation, 271 std::shared_ptr<PCHContainerOperations> PCHContainerOps) { 272 // Show the invocation, with -v. 273 if (Invocation->getHeaderSearchOpts().Verbose) { 274 llvm::errs() << "clang Invocation:\n"; 275 Compilation->getJobs().Print(llvm::errs(), "\n", true); 276 llvm::errs() << "\n"; 277 } 278 279 return Action->runInvocation(Invocation, Files, PCHContainerOps, 280 DiagConsumer); 281 } 282 283 bool FrontendActionFactory::runInvocation( 284 CompilerInvocation *Invocation, FileManager *Files, 285 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 286 DiagnosticConsumer *DiagConsumer) { 287 // Create a compiler instance to handle the actual work. 288 clang::CompilerInstance Compiler(PCHContainerOps); 289 Compiler.setInvocation(Invocation); 290 Compiler.setFileManager(Files); 291 292 // The FrontendAction can have lifetime requirements for Compiler or its 293 // members, and we need to ensure it's deleted earlier than Compiler. So we 294 // pass it to an std::unique_ptr declared after the Compiler variable. 295 std::unique_ptr<FrontendAction> ScopedToolAction(create()); 296 297 // Create the compiler's actual diagnostics engine. 298 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false); 299 if (!Compiler.hasDiagnostics()) 300 return false; 301 302 Compiler.createSourceManager(*Files); 303 304 const bool Success = Compiler.ExecuteAction(*ScopedToolAction); 305 306 Files->clearStatCaches(); 307 return Success; 308 } 309 310 ClangTool::ClangTool(const CompilationDatabase &Compilations, 311 ArrayRef<std::string> SourcePaths, 312 std::shared_ptr<PCHContainerOperations> PCHContainerOps) 313 : Compilations(Compilations), SourcePaths(SourcePaths), 314 PCHContainerOps(PCHContainerOps), 315 OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())), 316 InMemoryFileSystem(new vfs::InMemoryFileSystem), 317 Files(new FileManager(FileSystemOptions(), OverlayFileSystem)), 318 DiagConsumer(nullptr) { 319 OverlayFileSystem->pushOverlay(InMemoryFileSystem); 320 appendArgumentsAdjuster(getClangStripOutputAdjuster()); 321 appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster()); 322 } 323 324 ClangTool::~ClangTool() {} 325 326 void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) { 327 MappedFileContents.push_back(std::make_pair(FilePath, Content)); 328 } 329 330 void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) { 331 if (ArgsAdjuster) 332 ArgsAdjuster = combineAdjusters(ArgsAdjuster, Adjuster); 333 else 334 ArgsAdjuster = Adjuster; 335 } 336 337 void ClangTool::clearArgumentsAdjusters() { 338 ArgsAdjuster = nullptr; 339 } 340 341 int ClangTool::run(ToolAction *Action) { 342 // Exists solely for the purpose of lookup of the resource path. 343 // This just needs to be some symbol in the binary. 344 static int StaticSymbol; 345 // The driver detects the builtin header path based on the path of the 346 // executable. 347 // FIXME: On linux, GetMainExecutable is independent of the value of the 348 // first argument, thus allowing ClangTool and runToolOnCode to just 349 // pass in made-up names here. Make sure this works on other platforms. 350 std::string MainExecutable = 351 llvm::sys::fs::getMainExecutable("clang_tool", &StaticSymbol); 352 353 llvm::SmallString<128> InitialDirectory; 354 if (std::error_code EC = llvm::sys::fs::current_path(InitialDirectory)) 355 llvm::report_fatal_error("Cannot detect current path: " + 356 Twine(EC.message())); 357 358 // First insert all absolute paths into the in-memory VFS. These are global 359 // for all compile commands. 360 if (SeenWorkingDirectories.insert("/").second) 361 for (const auto &MappedFile : MappedFileContents) 362 if (llvm::sys::path::is_absolute(MappedFile.first)) 363 InMemoryFileSystem->addFile( 364 MappedFile.first, 0, 365 llvm::MemoryBuffer::getMemBuffer(MappedFile.second)); 366 367 bool ProcessingFailed = false; 368 for (const auto &SourcePath : SourcePaths) { 369 std::string File(getAbsolutePath(SourcePath)); 370 371 // Currently implementations of CompilationDatabase::getCompileCommands can 372 // change the state of the file system (e.g. prepare generated headers), so 373 // this method needs to run right before we invoke the tool, as the next 374 // file may require a different (incompatible) state of the file system. 375 // 376 // FIXME: Make the compilation database interface more explicit about the 377 // requirements to the order of invocation of its members. 378 std::vector<CompileCommand> CompileCommandsForFile = 379 Compilations.getCompileCommands(File); 380 if (CompileCommandsForFile.empty()) { 381 // FIXME: There are two use cases here: doing a fuzzy 382 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care 383 // about the .cc files that were not found, and the use case where I 384 // specify all files I want to run over explicitly, where this should 385 // be an error. We'll want to add an option for this. 386 llvm::errs() << "Skipping " << File << ". Compile command not found.\n"; 387 continue; 388 } 389 for (CompileCommand &CompileCommand : CompileCommandsForFile) { 390 // FIXME: chdir is thread hostile; on the other hand, creating the same 391 // behavior as chdir is complex: chdir resolves the path once, thus 392 // guaranteeing that all subsequent relative path operations work 393 // on the same path the original chdir resulted in. This makes a 394 // difference for example on network filesystems, where symlinks might be 395 // switched during runtime of the tool. Fixing this depends on having a 396 // file system abstraction that allows openat() style interactions. 397 if (OverlayFileSystem->setCurrentWorkingDirectory( 398 CompileCommand.Directory)) 399 llvm::report_fatal_error("Cannot chdir into \"" + 400 Twine(CompileCommand.Directory) + "\n!"); 401 402 // Now fill the in-memory VFS with the relative file mappings so it will 403 // have the correct relative paths. We never remove mappings but that 404 // should be fine. 405 if (SeenWorkingDirectories.insert(CompileCommand.Directory).second) 406 for (const auto &MappedFile : MappedFileContents) 407 if (!llvm::sys::path::is_absolute(MappedFile.first)) 408 InMemoryFileSystem->addFile( 409 MappedFile.first, 0, 410 llvm::MemoryBuffer::getMemBuffer(MappedFile.second)); 411 412 std::vector<std::string> CommandLine = CompileCommand.CommandLine; 413 if (ArgsAdjuster) 414 CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename); 415 assert(!CommandLine.empty()); 416 CommandLine[0] = MainExecutable; 417 // FIXME: We need a callback mechanism for the tool writer to output a 418 // customized message for each file. 419 DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; }); 420 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(), 421 PCHContainerOps); 422 Invocation.setDiagnosticConsumer(DiagConsumer); 423 424 if (!Invocation.run()) { 425 // FIXME: Diagnostics should be used instead. 426 llvm::errs() << "Error while processing " << File << ".\n"; 427 ProcessingFailed = true; 428 } 429 // Return to the initial directory to correctly resolve next file by 430 // relative path. 431 if (OverlayFileSystem->setCurrentWorkingDirectory(InitialDirectory.c_str())) 432 llvm::report_fatal_error("Cannot chdir into \"" + 433 Twine(InitialDirectory) + "\n!"); 434 } 435 } 436 return ProcessingFailed ? 1 : 0; 437 } 438 439 namespace { 440 441 class ASTBuilderAction : public ToolAction { 442 std::vector<std::unique_ptr<ASTUnit>> &ASTs; 443 444 public: 445 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {} 446 447 bool runInvocation(CompilerInvocation *Invocation, FileManager *Files, 448 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 449 DiagnosticConsumer *DiagConsumer) override { 450 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation( 451 Invocation, PCHContainerOps, 452 CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(), 453 DiagConsumer, 454 /*ShouldOwnClient=*/false), 455 Files); 456 if (!AST) 457 return false; 458 459 ASTs.push_back(std::move(AST)); 460 return true; 461 } 462 }; 463 464 } 465 466 int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) { 467 ASTBuilderAction Action(ASTs); 468 return run(&Action); 469 } 470 471 std::unique_ptr<ASTUnit> 472 buildASTFromCode(const Twine &Code, const Twine &FileName, 473 std::shared_ptr<PCHContainerOperations> PCHContainerOps) { 474 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName, 475 "clang-tool", PCHContainerOps); 476 } 477 478 std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs( 479 const Twine &Code, const std::vector<std::string> &Args, 480 const Twine &FileName, const Twine &ToolName, 481 std::shared_ptr<PCHContainerOperations> PCHContainerOps) { 482 SmallString<16> FileNameStorage; 483 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage); 484 485 std::vector<std::unique_ptr<ASTUnit>> ASTs; 486 ASTBuilderAction Action(ASTs); 487 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem( 488 new vfs::OverlayFileSystem(vfs::getRealFileSystem())); 489 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem( 490 new vfs::InMemoryFileSystem); 491 OverlayFileSystem->pushOverlay(InMemoryFileSystem); 492 llvm::IntrusiveRefCntPtr<FileManager> Files( 493 new FileManager(FileSystemOptions(), OverlayFileSystem)); 494 ToolInvocation Invocation(getSyntaxOnlyToolArgs(ToolName, Args, FileNameRef), 495 &Action, Files.get(), PCHContainerOps); 496 497 SmallString<1024> CodeStorage; 498 InMemoryFileSystem->addFile(FileNameRef, 0, 499 llvm::MemoryBuffer::getMemBuffer( 500 Code.toNullTerminatedStringRef(CodeStorage))); 501 if (!Invocation.run()) 502 return nullptr; 503 504 assert(ASTs.size() == 1); 505 return std::move(ASTs[0]); 506 } 507 508 } // end namespace tooling 509 } // end namespace clang 510