Tooling.cpp 17 KB

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