744 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8//9// This file implements functions to run clang tools standalone instead10// 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/DiagnosticFrontend.h"17#include "clang/Basic/DiagnosticIDs.h"18#include "clang/Basic/DiagnosticOptions.h"19#include "clang/Basic/FileManager.h"20#include "clang/Basic/FileSystemOptions.h"21#include "clang/Basic/LLVM.h"22#include "clang/Driver/Compilation.h"23#include "clang/Driver/Driver.h"24#include "clang/Driver/Job.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/FrontendOptions.h"31#include "clang/Frontend/TextDiagnosticPrinter.h"32#include "clang/Lex/HeaderSearchOptions.h"33#include "clang/Lex/PreprocessorOptions.h"34#include "clang/Options/OptionUtils.h"35#include "clang/Options/Options.h"36#include "clang/Tooling/ArgumentsAdjusters.h"37#include "clang/Tooling/CompilationDatabase.h"38#include "llvm/ADT/ArrayRef.h"39#include "llvm/ADT/IntrusiveRefCntPtr.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/CommandLine.h"46#include "llvm/Support/Debug.h"47#include "llvm/Support/ErrorHandling.h"48#include "llvm/Support/MemoryBuffer.h"49#include "llvm/Support/Path.h"50#include "llvm/Support/VirtualFileSystem.h"51#include "llvm/Support/raw_ostream.h"52#include "llvm/TargetParser/Host.h"53#include <cassert>54#include <cstring>55#include <memory>56#include <string>57#include <system_error>58#include <utility>59#include <vector>60 61#define DEBUG_TYPE "clang-tooling"62 63using namespace clang;64using namespace tooling;65 66ToolAction::~ToolAction() = default;67 68FrontendActionFactory::~FrontendActionFactory() = default;69 70// FIXME: This file contains structural duplication with other parts of the71// code that sets up a compiler to run tools on it, and we should refactor72// it to be based on the same framework.73 74/// Builds a clang driver initialized for running clang tools.75static driver::Driver *76newDriver(DiagnosticsEngine *Diagnostics, const char *BinaryName,77 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {78 driver::Driver *CompilerDriver =79 new driver::Driver(BinaryName, llvm::sys::getDefaultTargetTriple(),80 *Diagnostics, "clang LLVM compiler", std::move(VFS));81 CompilerDriver->setTitle("clang_based_tool");82 return CompilerDriver;83}84 85/// Decide whether extra compiler frontend commands can be ignored.86static bool ignoreExtraCC1Commands(const driver::Compilation *Compilation) {87 const driver::JobList &Jobs = Compilation->getJobs();88 const driver::ActionList &Actions = Compilation->getActions();89 90 bool OffloadCompilation = false;91 92 // Jobs and Actions look very different depending on whether the Clang tool93 // injected -fsyntax-only or not. Try to handle both cases here.94 95 for (const auto &Job : Jobs)96 if (StringRef(Job.getExecutable()) == "clang-offload-bundler")97 OffloadCompilation = true;98 99 if (Jobs.size() > 1) {100 for (auto *A : Actions){101 // On MacOSX real actions may end up being wrapped in BindArchAction102 if (isa<driver::BindArchAction>(A))103 A = *A->input_begin();104 if (isa<driver::OffloadAction>(A)) {105 // Offload compilation has 2 top-level actions, one (at the front) is106 // the original host compilation and the other is offload action107 // composed of at least one device compilation. For such case, general108 // tooling will consider host-compilation only. For tooling on device109 // compilation, device compilation only option, such as110 // `--cuda-device-only`, needs specifying.111 assert(Actions.size() > 1);112 assert(113 isa<driver::CompileJobAction>(Actions.front()) ||114 // On MacOSX real actions may end up being wrapped in115 // BindArchAction.116 (isa<driver::BindArchAction>(Actions.front()) &&117 isa<driver::CompileJobAction>(*Actions.front()->input_begin())));118 OffloadCompilation = true;119 break;120 }121 }122 }123 124 return OffloadCompilation;125}126 127namespace clang {128namespace tooling {129 130const llvm::opt::ArgStringList *131getCC1Arguments(DiagnosticsEngine *Diagnostics,132 driver::Compilation *Compilation) {133 const driver::JobList &Jobs = Compilation->getJobs();134 135 auto IsCC1Command = [](const driver::Command &Cmd) {136 return StringRef(Cmd.getCreator().getName()) == "clang";137 };138 139 auto IsSrcFile = [](const driver::InputInfo &II) {140 return isSrcFile(II.getType());141 };142 143 llvm::SmallVector<const driver::Command *, 1> CC1Jobs;144 for (const driver::Command &Job : Jobs)145 if (IsCC1Command(Job) && llvm::all_of(Job.getInputInfos(), IsSrcFile))146 CC1Jobs.push_back(&Job);147 148 // If there are no jobs for source files, try checking again for a single job149 // with any file type. This accepts a preprocessed file as input.150 if (CC1Jobs.empty())151 for (const driver::Command &Job : Jobs)152 if (IsCC1Command(Job))153 CC1Jobs.push_back(&Job);154 155 if (CC1Jobs.empty() ||156 (CC1Jobs.size() > 1 && !ignoreExtraCC1Commands(Compilation))) {157 SmallString<256> error_msg;158 llvm::raw_svector_ostream error_stream(error_msg);159 Jobs.Print(error_stream, "; ", true);160 Diagnostics->Report(diag::err_fe_expected_compiler_job)161 << error_stream.str();162 return nullptr;163 }164 165 return &CC1Jobs[0]->getArguments();166}167 168/// Returns a clang build invocation initialized from the CC1 flags.169CompilerInvocation *newInvocation(DiagnosticsEngine *Diagnostics,170 ArrayRef<const char *> CC1Args,171 const char *const BinaryName) {172 assert(!CC1Args.empty() && "Must at least contain the program name!");173 CompilerInvocation *Invocation = new CompilerInvocation;174 CompilerInvocation::CreateFromArgs(*Invocation, CC1Args, *Diagnostics,175 BinaryName);176 Invocation->getFrontendOpts().DisableFree = false;177 Invocation->getCodeGenOpts().DisableFree = false;178 return Invocation;179}180 181bool runToolOnCode(std::unique_ptr<FrontendAction> ToolAction,182 const Twine &Code, const Twine &FileName,183 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {184 return runToolOnCodeWithArgs(std::move(ToolAction), Code,185 std::vector<std::string>(), FileName,186 "clang-tool", std::move(PCHContainerOps));187}188 189} // namespace tooling190} // namespace clang191 192static std::vector<std::string>193getSyntaxOnlyToolArgs(const Twine &ToolName,194 const std::vector<std::string> &ExtraArgs,195 StringRef FileName) {196 std::vector<std::string> Args;197 Args.push_back(ToolName.str());198 Args.push_back("-fsyntax-only");199 llvm::append_range(Args, ExtraArgs);200 Args.push_back(FileName.str());201 return Args;202}203 204namespace clang {205namespace tooling {206 207bool runToolOnCodeWithArgs(208 std::unique_ptr<FrontendAction> ToolAction, const Twine &Code,209 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,210 const std::vector<std::string> &Args, const Twine &FileName,211 const Twine &ToolName,212 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {213 SmallString<16> FileNameStorage;214 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);215 216 llvm::IntrusiveRefCntPtr<FileManager> Files =217 llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(), VFS);218 ArgumentsAdjuster Adjuster = getClangStripDependencyFileAdjuster();219 ToolInvocation Invocation(220 getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef),221 std::move(ToolAction), Files.get(), std::move(PCHContainerOps));222 return Invocation.run();223}224 225bool runToolOnCodeWithArgs(226 std::unique_ptr<FrontendAction> ToolAction, const Twine &Code,227 const std::vector<std::string> &Args, const Twine &FileName,228 const Twine &ToolName,229 std::shared_ptr<PCHContainerOperations> PCHContainerOps,230 const FileContentMappings &VirtualMappedFiles) {231 auto OverlayFileSystem =232 llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(233 llvm::vfs::getRealFileSystem());234 auto InMemoryFileSystem =235 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();236 OverlayFileSystem->pushOverlay(InMemoryFileSystem);237 238 SmallString<1024> CodeStorage;239 InMemoryFileSystem->addFile(FileName, 0,240 llvm::MemoryBuffer::getMemBuffer(241 Code.toNullTerminatedStringRef(CodeStorage)));242 243 for (auto &FilenameWithContent : VirtualMappedFiles) {244 InMemoryFileSystem->addFile(245 FilenameWithContent.first, 0,246 llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));247 }248 249 return runToolOnCodeWithArgs(std::move(ToolAction), Code, OverlayFileSystem,250 Args, FileName, ToolName);251}252 253llvm::Expected<std::string> getAbsolutePath(llvm::vfs::FileSystem &FS,254 StringRef File) {255 StringRef RelativePath(File);256 // FIXME: Should '.\\' be accepted on Win32?257 RelativePath.consume_front("./");258 259 SmallString<1024> AbsolutePath = RelativePath;260 if (auto EC = FS.makeAbsolute(AbsolutePath))261 return llvm::errorCodeToError(EC);262 llvm::sys::path::native(AbsolutePath);263 return std::string(AbsolutePath);264}265 266std::string getAbsolutePath(StringRef File) {267 return llvm::cantFail(getAbsolutePath(*llvm::vfs::getRealFileSystem(), File));268}269 270void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,271 StringRef InvokedAs) {272 if (CommandLine.empty() || InvokedAs.empty())273 return;274 const auto &Table = getDriverOptTable();275 // --target=X276 StringRef TargetOPT = Table.getOption(options::OPT_target).getPrefixedName();277 // -target X278 StringRef TargetOPTLegacy =279 Table.getOption(options::OPT_target_legacy_spelling).getPrefixedName();280 // --driver-mode=X281 StringRef DriverModeOPT =282 Table.getOption(options::OPT_driver_mode).getPrefixedName();283 auto TargetMode =284 driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs);285 // No need to search for target args if we don't have a target/mode to insert.286 bool ShouldAddTarget = TargetMode.TargetIsValid;287 bool ShouldAddMode = TargetMode.DriverMode != nullptr;288 // Skip CommandLine[0].289 for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();290 ++Token) {291 StringRef TokenRef(*Token);292 ShouldAddTarget = ShouldAddTarget && !TokenRef.starts_with(TargetOPT) &&293 TokenRef != TargetOPTLegacy;294 ShouldAddMode = ShouldAddMode && !TokenRef.starts_with(DriverModeOPT);295 }296 if (ShouldAddMode) {297 CommandLine.insert(++CommandLine.begin(), TargetMode.DriverMode);298 }299 if (ShouldAddTarget) {300 CommandLine.insert(++CommandLine.begin(),301 (TargetOPT + TargetMode.TargetPrefix).str());302 }303}304 305void addExpandedResponseFiles(std::vector<std::string> &CommandLine,306 llvm::StringRef WorkingDir,307 llvm::cl::TokenizerCallback Tokenizer,308 llvm::vfs::FileSystem &FS) {309 bool SeenRSPFile = false;310 llvm::SmallVector<const char *, 20> Argv;311 Argv.reserve(CommandLine.size());312 for (auto &Arg : CommandLine) {313 Argv.push_back(Arg.c_str());314 if (!Arg.empty())315 SeenRSPFile |= Arg.front() == '@';316 }317 if (!SeenRSPFile)318 return;319 llvm::BumpPtrAllocator Alloc;320 llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer);321 llvm::Error Err =322 ECtx.setVFS(&FS).setCurrentDir(WorkingDir).expandResponseFiles(Argv);323 if (Err)324 llvm::errs() << Err;325 // Don't assign directly, Argv aliases CommandLine.326 std::vector<std::string> ExpandedArgv(Argv.begin(), Argv.end());327 CommandLine = std::move(ExpandedArgv);328}329 330} // namespace tooling331} // namespace clang332 333namespace {334 335class SingleFrontendActionFactory : public FrontendActionFactory {336 std::unique_ptr<FrontendAction> Action;337 338public:339 SingleFrontendActionFactory(std::unique_ptr<FrontendAction> Action)340 : Action(std::move(Action)) {}341 342 std::unique_ptr<FrontendAction> create() override {343 return std::move(Action);344 }345};346 347} // namespace348 349ToolInvocation::ToolInvocation(350 std::vector<std::string> CommandLine, ToolAction *Action,351 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)352 : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false),353 Files(Files), PCHContainerOps(std::move(PCHContainerOps)) {}354 355ToolInvocation::ToolInvocation(356 std::vector<std::string> CommandLine,357 std::unique_ptr<FrontendAction> FAction, FileManager *Files,358 std::shared_ptr<PCHContainerOperations> PCHContainerOps)359 : CommandLine(std::move(CommandLine)),360 Action(new SingleFrontendActionFactory(std::move(FAction))),361 OwnsAction(true), Files(Files),362 PCHContainerOps(std::move(PCHContainerOps)) {}363 364ToolInvocation::~ToolInvocation() {365 if (OwnsAction)366 delete Action;367}368 369bool ToolInvocation::run() {370 llvm::opt::ArgStringList Argv;371 for (const std::string &Str : CommandLine)372 Argv.push_back(Str.c_str());373 const char *const BinaryName = Argv[0];374 375 // Parse diagnostic options from the driver command-line only if none were376 // explicitly set.377 std::unique_ptr<DiagnosticOptions> ParsedDiagOpts;378 DiagnosticOptions *DiagOpts = this->DiagOpts;379 if (!DiagOpts) {380 ParsedDiagOpts = CreateAndPopulateDiagOpts(Argv);381 DiagOpts = &*ParsedDiagOpts;382 }383 384 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), *DiagOpts);385 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics =386 CompilerInstance::createDiagnostics(387 Files->getVirtualFileSystem(), *DiagOpts,388 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);389 // Although `Diagnostics` are used only for command-line parsing, the custom390 // `DiagConsumer` might expect a `SourceManager` to be present.391 SourceManager SrcMgr(*Diagnostics, *Files);392 Diagnostics->setSourceManager(&SrcMgr);393 394 // We already have a cc1, just create an invocation.395 if (CommandLine.size() >= 2 && CommandLine[1] == "-cc1") {396 ArrayRef<const char *> CC1Args = ArrayRef(Argv).drop_front();397 std::unique_ptr<CompilerInvocation> Invocation(398 newInvocation(&*Diagnostics, CC1Args, BinaryName));399 if (Diagnostics->hasErrorOccurred())400 return false;401 return Action->runInvocation(std::move(Invocation), Files,402 std::move(PCHContainerOps), DiagConsumer);403 }404 405 const std::unique_ptr<driver::Driver> Driver(406 newDriver(&*Diagnostics, BinaryName, Files->getVirtualFileSystemPtr()));407 // The "input file not found" diagnostics from the driver are useful.408 // The driver is only aware of the VFS working directory, but some clients409 // change this at the FileManager level instead.410 // In this case the checks have false positives, so skip them.411 if (!Files->getFileSystemOpts().WorkingDir.empty())412 Driver->setCheckInputsExist(false);413 const std::unique_ptr<driver::Compilation> Compilation(414 Driver->BuildCompilation(llvm::ArrayRef(Argv)));415 if (!Compilation)416 return false;417 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(418 &*Diagnostics, Compilation.get());419 if (!CC1Args)420 return false;421 std::unique_ptr<CompilerInvocation> Invocation(422 newInvocation(&*Diagnostics, *CC1Args, BinaryName));423 return runInvocation(BinaryName, Compilation.get(), std::move(Invocation),424 std::move(PCHContainerOps));425}426 427bool ToolInvocation::runInvocation(428 const char *BinaryName, driver::Compilation *Compilation,429 std::shared_ptr<CompilerInvocation> Invocation,430 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {431 // Show the invocation, with -v.432 if (Invocation->getHeaderSearchOpts().Verbose) {433 llvm::errs() << "clang Invocation:\n";434 Compilation->getJobs().Print(llvm::errs(), "\n", true);435 llvm::errs() << "\n";436 }437 438 return Action->runInvocation(std::move(Invocation), Files,439 std::move(PCHContainerOps), DiagConsumer);440}441 442bool FrontendActionFactory::runInvocation(443 std::shared_ptr<CompilerInvocation> Invocation, FileManager *Files,444 std::shared_ptr<PCHContainerOperations> PCHContainerOps,445 DiagnosticConsumer *DiagConsumer) {446 // Create a compiler instance to handle the actual work.447 CompilerInstance Compiler(std::move(Invocation), std::move(PCHContainerOps));448 Compiler.setVirtualFileSystem(Files->getVirtualFileSystemPtr());449 Compiler.setFileManager(Files);450 451 // The FrontendAction can have lifetime requirements for Compiler or its452 // members, and we need to ensure it's deleted earlier than Compiler. So we453 // pass it to an std::unique_ptr declared after the Compiler variable.454 std::unique_ptr<FrontendAction> ScopedToolAction(create());455 456 // Create the compiler's actual diagnostics engine.457 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);458 if (!Compiler.hasDiagnostics())459 return false;460 461 Compiler.createSourceManager();462 463 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);464 465 Files->clearStatCache();466 return Success;467}468 469ClangTool::ClangTool(const CompilationDatabase &Compilations,470 ArrayRef<std::string> SourcePaths,471 std::shared_ptr<PCHContainerOperations> PCHContainerOps,472 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,473 IntrusiveRefCntPtr<FileManager> Files)474 : Compilations(Compilations), SourcePaths(SourcePaths),475 PCHContainerOps(std::move(PCHContainerOps)),476 OverlayFileSystem(llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(477 std::move(BaseFS))),478 InMemoryFileSystem(479 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>()),480 Files(Files ? Files481 : llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),482 OverlayFileSystem)) {483 OverlayFileSystem->pushOverlay(InMemoryFileSystem);484 appendArgumentsAdjuster(getClangStripOutputAdjuster());485 appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());486 appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());487 if (Files)488 Files->setVirtualFileSystem(OverlayFileSystem);489}490 491ClangTool::~ClangTool() = default;492 493void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {494 MappedFileContents.push_back(std::make_pair(FilePath, Content));495}496 497void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {498 ArgsAdjuster = combineAdjusters(std::move(ArgsAdjuster), std::move(Adjuster));499}500 501void ClangTool::clearArgumentsAdjusters() {502 ArgsAdjuster = nullptr;503}504 505static void injectResourceDir(CommandLineArguments &Args, const char *Argv0,506 void *MainAddr) {507 // Allow users to override the resource dir.508 for (StringRef Arg : Args)509 if (Arg.starts_with("-resource-dir"))510 return;511 512 // If there's no override in place add our resource dir.513 Args = getInsertArgumentAdjuster(514 ("-resource-dir=" + GetResourcesPath(Argv0, MainAddr)).c_str())(Args, "");515}516 517int ClangTool::run(ToolAction *Action) {518 // Exists solely for the purpose of lookup of the resource path.519 // This just needs to be some symbol in the binary.520 static int StaticSymbol;521 522 // First insert all absolute paths into the in-memory VFS. These are global523 // for all compile commands.524 if (SeenWorkingDirectories.insert("/").second)525 for (const auto &MappedFile : MappedFileContents)526 if (llvm::sys::path::is_absolute(MappedFile.first))527 InMemoryFileSystem->addFile(528 MappedFile.first, 0,529 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));530 531 bool ProcessingFailed = false;532 bool FileSkipped = false;533 // Compute all absolute paths before we run any actions, as those will change534 // the working directory.535 std::vector<std::string> AbsolutePaths;536 AbsolutePaths.reserve(SourcePaths.size());537 for (const auto &SourcePath : SourcePaths) {538 auto AbsPath = getAbsolutePath(*OverlayFileSystem, SourcePath);539 if (!AbsPath) {540 llvm::errs() << "Skipping " << SourcePath541 << ". Error while getting an absolute path: "542 << llvm::toString(AbsPath.takeError()) << "\n";543 continue;544 }545 AbsolutePaths.push_back(std::move(*AbsPath));546 }547 548 // Remember the working directory in case we need to restore it.549 std::string InitialWorkingDir;550 if (auto CWD = OverlayFileSystem->getCurrentWorkingDirectory()) {551 InitialWorkingDir = std::move(*CWD);552 } else {553 llvm::errs() << "Could not get working directory: "554 << CWD.getError().message() << "\n";555 }556 557 size_t NumOfTotalFiles = AbsolutePaths.size();558 unsigned ProcessedFileCounter = 0;559 for (llvm::StringRef File : AbsolutePaths) {560 // Currently implementations of CompilationDatabase::getCompileCommands can561 // change the state of the file system (e.g. prepare generated headers), so562 // this method needs to run right before we invoke the tool, as the next563 // file may require a different (incompatible) state of the file system.564 //565 // FIXME: Make the compilation database interface more explicit about the566 // requirements to the order of invocation of its members.567 std::vector<CompileCommand> CompileCommandsForFile =568 Compilations.getCompileCommands(File);569 if (CompileCommandsForFile.empty()) {570 llvm::errs() << "Skipping " << File << ". Compile command not found.\n";571 FileSkipped = true;572 continue;573 }574 for (CompileCommand &CompileCommand : CompileCommandsForFile) {575 // If the 'directory' field of the compilation database is empty, display576 // an error and use the working directory instead.577 StringRef Directory = CompileCommand.Directory;578 if (Directory.empty()) {579 llvm::errs() << "'directory' field of compilation database is empty; "580 "using the current working directory instead.\n";581 Directory = InitialWorkingDir;582 }583 584 // FIXME: chdir is thread hostile; on the other hand, creating the same585 // behavior as chdir is complex: chdir resolves the path once, thus586 // guaranteeing that all subsequent relative path operations work587 // on the same path the original chdir resulted in. This makes a588 // difference for example on network filesystems, where symlinks might be589 // switched during runtime of the tool. Fixing this depends on having a590 // file system abstraction that allows openat() style interactions.591 if (OverlayFileSystem->setCurrentWorkingDirectory(Directory))592 llvm::report_fatal_error("Cannot chdir into \"" + Twine(Directory) +593 "\"!");594 595 // Now fill the in-memory VFS with the relative file mappings so it will596 // have the correct relative paths. We never remove mappings but that597 // should be fine.598 if (SeenWorkingDirectories.insert(Directory).second)599 for (const auto &MappedFile : MappedFileContents)600 if (!llvm::sys::path::is_absolute(MappedFile.first))601 InMemoryFileSystem->addFile(602 MappedFile.first, 0,603 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));604 605 std::vector<std::string> CommandLine = CompileCommand.CommandLine;606 if (ArgsAdjuster)607 CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);608 assert(!CommandLine.empty());609 610 // Add the resource dir based on the binary of this tool. argv[0] in the611 // compilation database may refer to a different compiler and we want to612 // pick up the very same standard library that compiler is using. The613 // builtin headers in the resource dir need to match the exact clang614 // version the tool is using.615 // FIXME: On linux, GetMainExecutable is independent of the value of the616 // first argument, thus allowing ClangTool and runToolOnCode to just617 // pass in made-up names here. Make sure this works on other platforms.618 injectResourceDir(CommandLine, "clang_tool", &StaticSymbol);619 620 // FIXME: We need a callback mechanism for the tool writer to output a621 // customized message for each file.622 if (NumOfTotalFiles > 1)623 llvm::errs() << "[" + std::to_string(++ProcessedFileCounter) + "/" +624 std::to_string(NumOfTotalFiles) +625 "] Processing file " + File626 << ".\n";627 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),628 PCHContainerOps);629 Invocation.setDiagnosticConsumer(DiagConsumer);630 631 if (!Invocation.run()) {632 // FIXME: Diagnostics should be used instead.633 if (PrintErrorMessage)634 llvm::errs() << "Error while processing " << File << ".\n";635 ProcessingFailed = true;636 }637 }638 }639 640 if (!InitialWorkingDir.empty()) {641 if (auto EC =642 OverlayFileSystem->setCurrentWorkingDirectory(InitialWorkingDir))643 llvm::errs() << "Error when trying to restore working dir: "644 << EC.message() << "\n";645 }646 return ProcessingFailed ? 1 : (FileSkipped ? 2 : 0);647}648 649namespace {650 651class ASTBuilderAction : public ToolAction {652 std::vector<std::unique_ptr<ASTUnit>> &ASTs;653 CaptureDiagsKind CaptureKind;654 655public:656 ASTBuilderAction(657 std::vector<std::unique_ptr<ASTUnit>> &ASTs,658 CaptureDiagsKind CaptureDiagnosticsKind = CaptureDiagsKind::None)659 : ASTs(ASTs), CaptureKind(CaptureDiagnosticsKind) {}660 661 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,662 FileManager *Files,663 std::shared_ptr<PCHContainerOperations> PCHContainerOps,664 DiagnosticConsumer *DiagConsumer) override {665 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(666 Invocation, std::move(PCHContainerOps), nullptr,667 CompilerInstance::createDiagnostics(Files->getVirtualFileSystem(),668 Invocation->getDiagnosticOpts(),669 DiagConsumer,670 /*ShouldOwnClient=*/false),671 Files, false, CaptureKind);672 if (!AST)673 return false;674 675 ASTs.push_back(std::move(AST));676 return true;677 }678};679 680} // namespace681 682int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {683 ASTBuilderAction Action(ASTs);684 return run(&Action);685}686 687void ClangTool::setPrintErrorMessage(bool PrintErrorMessage) {688 this->PrintErrorMessage = PrintErrorMessage;689}690 691namespace clang {692namespace tooling {693 694std::unique_ptr<ASTUnit>695buildASTFromCode(StringRef Code, StringRef FileName,696 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {697 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,698 "clang-tool", std::move(PCHContainerOps));699}700 701std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(702 StringRef Code, const std::vector<std::string> &Args, StringRef FileName,703 StringRef ToolName, std::shared_ptr<PCHContainerOperations> PCHContainerOps,704 ArgumentsAdjuster Adjuster, const FileContentMappings &VirtualMappedFiles,705 DiagnosticConsumer *DiagConsumer,706 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,707 CaptureDiagsKind CaptureKind) {708 std::vector<std::unique_ptr<ASTUnit>> ASTs;709 710 ASTBuilderAction Action(ASTs, CaptureKind);711 712 auto OverlayFileSystem =713 llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(714 std::move(BaseFS));715 auto InMemoryFileSystem =716 llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();717 OverlayFileSystem->pushOverlay(InMemoryFileSystem);718 llvm::IntrusiveRefCntPtr<FileManager> Files =719 llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),720 OverlayFileSystem);721 722 ToolInvocation Invocation(723 getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileName), FileName),724 &Action, Files.get(), std::move(PCHContainerOps));725 Invocation.setDiagnosticConsumer(DiagConsumer);726 727 InMemoryFileSystem->addFile(FileName, 0,728 llvm::MemoryBuffer::getMemBufferCopy(Code));729 for (auto &FilenameWithContent : VirtualMappedFiles) {730 InMemoryFileSystem->addFile(731 FilenameWithContent.first, 0,732 llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));733 }734 735 if (!Invocation.run())736 return nullptr;737 738 assert(ASTs.size() == 1);739 return std::move(ASTs[0]);740}741 742} // namespace tooling743} // namespace clang744