blob: 69a4611e64581e12e87317dd274cb1b240e72b8e [file] [log] [blame]
Manuel Klimek47c245a2012-04-04 12:07:46 +00001//===--- 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"
Peter Collingbournec689ee72013-11-06 20:12:45 +000016#include "clang/AST/ASTConsumer.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000017#include "clang/Driver/Compilation.h"
18#include "clang/Driver/Driver.h"
19#include "clang/Driver/Tool.h"
Manuel Klimek9b30e2b2015-10-06 10:45:03 +000020#include "clang/Driver/ToolChain.h"
Peter Collingbournec689ee72013-11-06 20:12:45 +000021#include "clang/Frontend/ASTUnit.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000022#include "clang/Frontend/CompilerInstance.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000023#include "clang/Frontend/FrontendDiagnostic.h"
24#include "clang/Frontend/TextDiagnosticPrinter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Tooling/ArgumentsAdjusters.h"
26#include "clang/Tooling/CompilationDatabase.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000027#include "llvm/ADT/STLExtras.h"
Alp Toker1d257e12014-06-04 03:28:55 +000028#include "llvm/Config/llvm-config.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000029#include "llvm/Option/Option.h"
Edwin Vane34794c52013-03-15 20:14:01 +000030#include "llvm/Support/Debug.h"
NAKAMURA Takumif0c87792012-04-04 13:59:36 +000031#include "llvm/Support/FileSystem.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000032#include "llvm/Support/Host.h"
33#include "llvm/Support/raw_ostream.h"
Benjamin Kramercfeacf52016-05-27 14:27:13 +000034#include <utility>
Manuel Klimek47c245a2012-04-04 12:07:46 +000035
Chandler Carruth57f5fbe2014-04-21 22:55:36 +000036#define DEBUG_TYPE "clang-tooling"
37
Manuel Klimek47c245a2012-04-04 12:07:46 +000038namespace clang {
39namespace tooling {
40
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000041ToolAction::~ToolAction() {}
Peter Collingbournec689ee72013-11-06 20:12:45 +000042
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000043FrontendActionFactory::~FrontendActionFactory() {}
Manuel Klimek47c245a2012-04-04 12:07:46 +000044
45// FIXME: This file contains structural duplication with other parts of the
46// code that sets up a compiler to run tools on it, and we should refactor
47// it to be based on the same framework.
48
49/// \brief Builds a clang driver initialized for running clang tools.
Benjamin Kramer407eb792015-10-09 13:03:25 +000050static clang::driver::Driver *newDriver(
51 clang::DiagnosticsEngine *Diagnostics, const char *BinaryName,
52 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000053 clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
Benjamin Kramer407eb792015-10-09 13:03:25 +000054 BinaryName, llvm::sys::getDefaultTargetTriple(), *Diagnostics, VFS);
Manuel Klimek47c245a2012-04-04 12:07:46 +000055 CompilerDriver->setTitle("clang_based_tool");
56 return CompilerDriver;
57}
58
59/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
60///
61/// Returns NULL on error.
Reid Kleckner898229a2013-06-14 17:17:23 +000062static const llvm::opt::ArgStringList *getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +000063 clang::DiagnosticsEngine *Diagnostics,
64 clang::driver::Compilation *Compilation) {
65 // We expect to get back exactly one Command job, if we didn't something
66 // failed. Extract that job from the Compilation.
67 const clang::driver::JobList &Jobs = Compilation->getJobs();
Justin Bogneraab97922014-10-03 01:04:53 +000068 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000069 SmallString<256> error_msg;
Manuel Klimek47c245a2012-04-04 12:07:46 +000070 llvm::raw_svector_ostream error_stream(error_msg);
Hans Wennborgb212b342013-09-12 18:23:34 +000071 Jobs.Print(error_stream, "; ", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +000072 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
73 << error_stream.str();
Craig Topperccbc35e2014-05-20 04:51:16 +000074 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +000075 }
76
77 // The one job we find should be to invoke clang again.
David Blaikiec11bf802014-09-04 16:04:28 +000078 const clang::driver::Command &Cmd =
Justin Bogneraab97922014-10-03 01:04:53 +000079 cast<clang::driver::Command>(*Jobs.begin());
David Blaikiec11bf802014-09-04 16:04:28 +000080 if (StringRef(Cmd.getCreator().getName()) != "clang") {
Manuel Klimek47c245a2012-04-04 12:07:46 +000081 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
Craig Topperccbc35e2014-05-20 04:51:16 +000082 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +000083 }
84
David Blaikiec11bf802014-09-04 16:04:28 +000085 return &Cmd.getArguments();
Manuel Klimek47c245a2012-04-04 12:07:46 +000086}
87
88/// \brief Returns a clang build invocation initialized from the CC1 flags.
Manuel Klimekbea7dfb2015-03-28 00:42:36 +000089clang::CompilerInvocation *newInvocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +000090 clang::DiagnosticsEngine *Diagnostics,
Reid Kleckner898229a2013-06-14 17:17:23 +000091 const llvm::opt::ArgStringList &CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000092 assert(!CC1Args.empty() && "Must at least contain the program name!");
93 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
94 clang::CompilerInvocation::CreateFromArgs(
95 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
96 *Diagnostics);
97 Invocation->getFrontendOpts().DisableFree = false;
Nick Lewycky39dc9f82013-06-25 17:01:21 +000098 Invocation->getCodeGenOpts().DisableFree = false;
Peter Collingbournec0423b32014-03-02 23:37:26 +000099 Invocation->getDependencyOutputOpts() = DependencyOutputOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000100 return Invocation;
101}
102
103bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000104 const Twine &FileName,
105 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
106 return runToolOnCodeWithArgs(ToolAction, Code, std::vector<std::string>(),
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000107 FileName, "clang-tool", PCHContainerOps);
Nico Weber077a53e2012-08-30 02:02:19 +0000108}
109
Peter Collingbournec689ee72013-11-06 20:12:45 +0000110static std::vector<std::string>
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000111getSyntaxOnlyToolArgs(const Twine &ToolName,
112 const std::vector<std::string> &ExtraArgs,
Peter Collingbournec689ee72013-11-06 20:12:45 +0000113 StringRef FileName) {
114 std::vector<std::string> Args;
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000115 Args.push_back(ToolName.str());
Peter Collingbournec689ee72013-11-06 20:12:45 +0000116 Args.push_back("-fsyntax-only");
117 Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
118 Args.push_back(FileName.str());
119 return Args;
120}
121
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000122bool runToolOnCodeWithArgs(
123 clang::FrontendAction *ToolAction, const Twine &Code,
124 const std::vector<std::string> &Args, const Twine &FileName,
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000125 const Twine &ToolName,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000126 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
127 const FileContentMappings &VirtualMappedFiles) {
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000128
Manuel Klimek47c245a2012-04-04 12:07:46 +0000129 SmallString<16> FileNameStorage;
130 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000131 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
132 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
133 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
134 new vfs::InMemoryFileSystem);
135 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000136 llvm::IntrusiveRefCntPtr<FileManager> Files(
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000137 new FileManager(FileSystemOptions(), OverlayFileSystem));
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000138 ToolInvocation Invocation(getSyntaxOnlyToolArgs(ToolName, Args, FileNameRef),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000139 ToolAction, Files.get(), PCHContainerOps);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000140
141 SmallString<1024> CodeStorage;
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000142 InMemoryFileSystem->addFile(FileNameRef, 0,
143 llvm::MemoryBuffer::getMemBuffer(
144 Code.toNullTerminatedStringRef(CodeStorage)));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000145
146 for (auto &FilenameWithContent : VirtualMappedFiles) {
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000147 InMemoryFileSystem->addFile(
148 FilenameWithContent.first, 0,
149 llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000150 }
151
Manuel Klimek47c245a2012-04-04 12:07:46 +0000152 return Invocation.run();
153}
154
Manuel Klimek65fd0e12012-07-10 13:10:51 +0000155std::string getAbsolutePath(StringRef File) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000156 StringRef RelativePath(File);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000157 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimek47c245a2012-04-04 12:07:46 +0000158 if (RelativePath.startswith("./")) {
159 RelativePath = RelativePath.substr(strlen("./"));
160 }
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000161
162 SmallString<1024> AbsolutePath = RelativePath;
Rafael Espindolac0809172014-06-12 14:02:15 +0000163 std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000164 assert(!EC);
Rafael Espindola0b8e4a12013-08-10 04:25:53 +0000165 (void)EC;
Benjamin Kramer2d4d8cb2013-09-11 11:23:15 +0000166 llvm::sys::path::native(AbsolutePath);
167 return AbsolutePath.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000168}
169
Manuel Klimek9b30e2b2015-10-06 10:45:03 +0000170void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
171 StringRef InvokedAs) {
172 if (!CommandLine.empty() && !InvokedAs.empty()) {
173 bool AlreadyHasTarget = false;
174 bool AlreadyHasMode = false;
175 // Skip CommandLine[0].
176 for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();
177 ++Token) {
178 StringRef TokenRef(*Token);
179 AlreadyHasTarget |=
180 (TokenRef == "-target" || TokenRef.startswith("-target="));
181 AlreadyHasMode |= (TokenRef == "--driver-mode" ||
182 TokenRef.startswith("--driver-mode="));
183 }
184 auto TargetMode =
185 clang::driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs);
186 if (!AlreadyHasMode && !TargetMode.second.empty()) {
187 CommandLine.insert(++CommandLine.begin(), TargetMode.second);
188 }
189 if (!AlreadyHasTarget && !TargetMode.first.empty()) {
190 CommandLine.insert(++CommandLine.begin(), {"-target", TargetMode.first});
191 }
192 }
193}
194
Peter Collingbournec689ee72013-11-06 20:12:45 +0000195namespace {
196
197class SingleFrontendActionFactory : public FrontendActionFactory {
198 FrontendAction *Action;
199
200public:
201 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
202
Craig Topperfb6b25b2014-03-15 04:29:04 +0000203 FrontendAction *create() override { return Action; }
Peter Collingbournec689ee72013-11-06 20:12:45 +0000204};
205
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000206}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000207
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000208ToolInvocation::ToolInvocation(
209 std::vector<std::string> CommandLine, ToolAction *Action,
210 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
211 : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false),
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000212 Files(Files), PCHContainerOps(std::move(PCHContainerOps)),
213 DiagConsumer(nullptr) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000214
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000215ToolInvocation::ToolInvocation(
216 std::vector<std::string> CommandLine, FrontendAction *FAction,
217 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000218 : CommandLine(std::move(CommandLine)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000219 Action(new SingleFrontendActionFactory(FAction)), OwnsAction(true),
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000220 Files(Files), PCHContainerOps(std::move(PCHContainerOps)),
221 DiagConsumer(nullptr) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000222
223ToolInvocation::~ToolInvocation() {
224 if (OwnsAction)
225 delete Action;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000226}
227
228void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi4de31652012-06-02 15:34:21 +0000229 SmallString<1024> PathStorage;
230 llvm::sys::path::native(FilePath, PathStorage);
231 MappedFileContents[PathStorage] = Content;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000232}
233
234bool ToolInvocation::run() {
235 std::vector<const char*> Argv;
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000236 for (const std::string &Str : CommandLine)
237 Argv.push_back(Str.c_str());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000238 const char *const BinaryName = Argv[0];
Douglas Gregor811db4e2012-10-23 22:26:28 +0000239 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000240 TextDiagnosticPrinter DiagnosticPrinter(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000241 llvm::errs(), &*DiagOpts);
242 DiagnosticsEngine Diagnostics(
Manuel Klimek64083012013-11-07 23:18:05 +0000243 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
244 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000245
Ahmed Charlesb8984322014-03-07 20:03:18 +0000246 const std::unique_ptr<clang::driver::Driver> Driver(
Benjamin Kramer407eb792015-10-09 13:03:25 +0000247 newDriver(&Diagnostics, BinaryName, Files->getVirtualFileSystem()));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000248 // Since the input might only be virtual, don't check whether it exists.
249 Driver->setCheckInputsExist(false);
Ahmed Charlesb8984322014-03-07 20:03:18 +0000250 const std::unique_ptr<clang::driver::Compilation> Compilation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000251 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
Reid Kleckner898229a2013-06-14 17:17:23 +0000252 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000253 &Diagnostics, Compilation.get());
Craig Topperccbc35e2014-05-20 04:51:16 +0000254 if (!CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000255 return false;
256 }
Ahmed Charlesb8984322014-03-07 20:03:18 +0000257 std::unique_ptr<clang::CompilerInvocation> Invocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000258 newInvocation(&Diagnostics, *CC1Args));
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000259 // FIXME: remove this when all users have migrated!
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000260 for (const auto &It : MappedFileContents) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000261 // Inject the code as the given file name into the preprocessor options.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000262 std::unique_ptr<llvm::MemoryBuffer> Input =
263 llvm::MemoryBuffer::getMemBuffer(It.getValue());
264 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
265 Input.release());
Peter Collingbournec689ee72013-11-06 20:12:45 +0000266 }
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000267 return runInvocation(BinaryName, Compilation.get(), Invocation.release(),
268 PCHContainerOps);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000269}
270
Manuel Klimek47c245a2012-04-04 12:07:46 +0000271bool ToolInvocation::runInvocation(
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000272 const char *BinaryName, clang::driver::Compilation *Compilation,
273 clang::CompilerInvocation *Invocation,
274 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000275 // Show the invocation, with -v.
276 if (Invocation->getHeaderSearchOpts().Verbose) {
277 llvm::errs() << "clang Invocation:\n";
Hans Wennborgb212b342013-09-12 18:23:34 +0000278 Compilation->getJobs().Print(llvm::errs(), "\n", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000279 llvm::errs() << "\n";
280 }
281
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000282 return Action->runInvocation(Invocation, Files, PCHContainerOps,
283 DiagConsumer);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000284}
285
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000286bool FrontendActionFactory::runInvocation(
287 CompilerInvocation *Invocation, FileManager *Files,
288 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
289 DiagnosticConsumer *DiagConsumer) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000290 // Create a compiler instance to handle the actual work.
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000291 clang::CompilerInstance Compiler(PCHContainerOps);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000292 Compiler.setInvocation(Invocation);
293 Compiler.setFileManager(Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000294
Peter Collingbournec689ee72013-11-06 20:12:45 +0000295 // The FrontendAction can have lifetime requirements for Compiler or its
296 // members, and we need to ensure it's deleted earlier than Compiler. So we
Ahmed Charlesb8984322014-03-07 20:03:18 +0000297 // pass it to an std::unique_ptr declared after the Compiler variable.
298 std::unique_ptr<FrontendAction> ScopedToolAction(create());
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000299
Alp Toker77273fc2014-05-16 13:45:29 +0000300 // Create the compiler's actual diagnostics engine.
Manuel Klimek64083012013-11-07 23:18:05 +0000301 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000302 if (!Compiler.hasDiagnostics())
303 return false;
304
305 Compiler.createSourceManager(*Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000306
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000307 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000308
Manuel Klimek3aad8552012-07-31 13:56:54 +0000309 Files->clearStatCaches();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000310 return Success;
311}
312
Manuel Klimek47c245a2012-04-04 12:07:46 +0000313ClangTool::ClangTool(const CompilationDatabase &Compilations,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000314 ArrayRef<std::string> SourcePaths,
315 std::shared_ptr<PCHContainerOperations> PCHContainerOps)
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000316 : Compilations(Compilations), SourcePaths(SourcePaths),
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000317 PCHContainerOps(std::move(PCHContainerOps)),
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000318 OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())),
319 InMemoryFileSystem(new vfs::InMemoryFileSystem),
320 Files(new FileManager(FileSystemOptions(), OverlayFileSystem)),
321 DiagConsumer(nullptr) {
322 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000323 appendArgumentsAdjuster(getClangStripOutputAdjuster());
324 appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000325}
326
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000327ClangTool::~ClangTool() {}
Manuel Klimek64083012013-11-07 23:18:05 +0000328
Manuel Klimek47c245a2012-04-04 12:07:46 +0000329void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
330 MappedFileContents.push_back(std::make_pair(FilePath, Content));
331}
332
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000333void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
334 if (ArgsAdjuster)
335 ArgsAdjuster = combineAdjusters(ArgsAdjuster, Adjuster);
336 else
337 ArgsAdjuster = Adjuster;
Manuel Klimekd91ac932013-06-04 14:44:44 +0000338}
339
340void ClangTool::clearArgumentsAdjusters() {
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000341 ArgsAdjuster = nullptr;
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000342}
343
Benjamin Kramerb5737c12016-04-21 10:18:18 +0000344static void injectResourceDir(CommandLineArguments &Args, const char *Argv0,
345 void *MainAddr) {
346 // Allow users to override the resource dir.
347 for (StringRef Arg : Args)
348 if (Arg.startswith("-resource-dir"))
349 return;
350
351 // If there's no override in place add our resource dir.
352 Args.push_back("-resource-dir=" +
353 CompilerInvocation::GetResourcesPath(Argv0, MainAddr));
354}
355
Peter Collingbournec689ee72013-11-06 20:12:45 +0000356int ClangTool::run(ToolAction *Action) {
Alexander Kornienko8388d242012-06-04 19:02:59 +0000357 // Exists solely for the purpose of lookup of the resource path.
358 // This just needs to be some symbol in the binary.
359 static int StaticSymbol;
Alexander Kornienko8388d242012-06-04 19:02:59 +0000360
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000361 llvm::SmallString<128> InitialDirectory;
362 if (std::error_code EC = llvm::sys::fs::current_path(InitialDirectory))
363 llvm::report_fatal_error("Cannot detect current path: " +
364 Twine(EC.message()));
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000365
366 // First insert all absolute paths into the in-memory VFS. These are global
367 // for all compile commands.
368 if (SeenWorkingDirectories.insert("/").second)
369 for (const auto &MappedFile : MappedFileContents)
370 if (llvm::sys::path::is_absolute(MappedFile.first))
371 InMemoryFileSystem->addFile(
372 MappedFile.first, 0,
373 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
374
Manuel Klimek47c245a2012-04-04 12:07:46 +0000375 bool ProcessingFailed = false;
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000376 for (const auto &SourcePath : SourcePaths) {
377 std::string File(getAbsolutePath(SourcePath));
378
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000379 // Currently implementations of CompilationDatabase::getCompileCommands can
380 // change the state of the file system (e.g. prepare generated headers), so
381 // this method needs to run right before we invoke the tool, as the next
382 // file may require a different (incompatible) state of the file system.
383 //
384 // FIXME: Make the compilation database interface more explicit about the
385 // requirements to the order of invocation of its members.
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000386 std::vector<CompileCommand> CompileCommandsForFile =
387 Compilations.getCompileCommands(File);
388 if (CompileCommandsForFile.empty()) {
389 // FIXME: There are two use cases here: doing a fuzzy
390 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
391 // about the .cc files that were not found, and the use case where I
392 // specify all files I want to run over explicitly, where this should
393 // be an error. We'll want to add an option for this.
394 llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
395 continue;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000396 }
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000397 for (CompileCommand &CompileCommand : CompileCommandsForFile) {
398 // FIXME: chdir is thread hostile; on the other hand, creating the same
399 // behavior as chdir is complex: chdir resolves the path once, thus
400 // guaranteeing that all subsequent relative path operations work
401 // on the same path the original chdir resulted in. This makes a
402 // difference for example on network filesystems, where symlinks might be
403 // switched during runtime of the tool. Fixing this depends on having a
404 // file system abstraction that allows openat() style interactions.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000405 if (OverlayFileSystem->setCurrentWorkingDirectory(
406 CompileCommand.Directory))
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000407 llvm::report_fatal_error("Cannot chdir into \"" +
408 Twine(CompileCommand.Directory) + "\n!");
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000409
410 // Now fill the in-memory VFS with the relative file mappings so it will
411 // have the correct relative paths. We never remove mappings but that
412 // should be fine.
413 if (SeenWorkingDirectories.insert(CompileCommand.Directory).second)
414 for (const auto &MappedFile : MappedFileContents)
415 if (!llvm::sys::path::is_absolute(MappedFile.first))
416 InMemoryFileSystem->addFile(
417 MappedFile.first, 0,
418 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
419
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000420 std::vector<std::string> CommandLine = CompileCommand.CommandLine;
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000421 if (ArgsAdjuster)
Alexander Kornienko857b10f2015-11-05 02:19:53 +0000422 CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000423 assert(!CommandLine.empty());
Benjamin Kramerb5737c12016-04-21 10:18:18 +0000424
425 // Add the resource dir based on the binary of this tool. argv[0] in the
426 // compilation database may refer to a different compiler and we want to
427 // pick up the very same standard library that compiler is using. The
428 // builtin headers in the resource dir need to match the exact clang
429 // version the tool is using.
430 // FIXME: On linux, GetMainExecutable is independent of the value of the
431 // first argument, thus allowing ClangTool and runToolOnCode to just
432 // pass in made-up names here. Make sure this works on other platforms.
433 injectResourceDir(CommandLine, "clang_tool", &StaticSymbol);
434
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000435 // FIXME: We need a callback mechanism for the tool writer to output a
436 // customized message for each file.
437 DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000438 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
439 PCHContainerOps);
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000440 Invocation.setDiagnosticConsumer(DiagConsumer);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000441
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000442 if (!Invocation.run()) {
443 // FIXME: Diagnostics should be used instead.
444 llvm::errs() << "Error while processing " << File << ".\n";
445 ProcessingFailed = true;
446 }
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000447 // Return to the initial directory to correctly resolve next file by
448 // relative path.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000449 if (OverlayFileSystem->setCurrentWorkingDirectory(InitialDirectory.c_str()))
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000450 llvm::report_fatal_error("Cannot chdir into \"" +
451 Twine(InitialDirectory) + "\n!");
Manuel Klimek47c245a2012-04-04 12:07:46 +0000452 }
453 }
454 return ProcessingFailed ? 1 : 0;
455}
456
Peter Collingbournec689ee72013-11-06 20:12:45 +0000457namespace {
458
459class ASTBuilderAction : public ToolAction {
David Blaikie39808ff2014-04-25 14:49:37 +0000460 std::vector<std::unique_ptr<ASTUnit>> &ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000461
462public:
David Blaikie39808ff2014-04-25 14:49:37 +0000463 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000464
Manuel Klimek64083012013-11-07 23:18:05 +0000465 bool runInvocation(CompilerInvocation *Invocation, FileManager *Files,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000466 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000467 DiagnosticConsumer *DiagConsumer) override {
David Blaikie103a2de2014-04-25 17:01:33 +0000468 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000469 Invocation, PCHContainerOps,
470 CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
471 DiagConsumer,
Benjamin Kramerbc632902015-10-06 14:45:20 +0000472 /*ShouldOwnClient=*/false),
473 Files);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000474 if (!AST)
475 return false;
476
David Blaikie39808ff2014-04-25 14:49:37 +0000477 ASTs.push_back(std::move(AST));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000478 return true;
479 }
480};
481
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000482}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000483
David Blaikie39808ff2014-04-25 14:49:37 +0000484int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000485 ASTBuilderAction Action(ASTs);
486 return run(&Action);
487}
488
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000489std::unique_ptr<ASTUnit>
490buildASTFromCode(const Twine &Code, const Twine &FileName,
491 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
492 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000493 "clang-tool", PCHContainerOps);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000494}
495
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000496std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
497 const Twine &Code, const std::vector<std::string> &Args,
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000498 const Twine &FileName, const Twine &ToolName,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000499 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000500 SmallString<16> FileNameStorage;
501 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
502
David Blaikie39808ff2014-04-25 14:49:37 +0000503 std::vector<std::unique_ptr<ASTUnit>> ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000504 ASTBuilderAction Action(ASTs);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000505 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
506 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
507 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
508 new vfs::InMemoryFileSystem);
509 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Benjamin Kramerfa3dcf22015-10-06 15:04:13 +0000510 llvm::IntrusiveRefCntPtr<FileManager> Files(
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000511 new FileManager(FileSystemOptions(), OverlayFileSystem));
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000512 ToolInvocation Invocation(getSyntaxOnlyToolArgs(ToolName, Args, FileNameRef),
513 &Action, Files.get(), PCHContainerOps);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000514
515 SmallString<1024> CodeStorage;
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000516 InMemoryFileSystem->addFile(FileNameRef, 0,
517 llvm::MemoryBuffer::getMemBuffer(
518 Code.toNullTerminatedStringRef(CodeStorage)));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000519 if (!Invocation.run())
Craig Topperccbc35e2014-05-20 04:51:16 +0000520 return nullptr;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000521
522 assert(ASTs.size() == 1);
David Blaikie103a2de2014-04-25 17:01:33 +0000523 return std::move(ASTs[0]);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000524}
525
Manuel Klimek47c245a2012-04-04 12:07:46 +0000526} // end namespace tooling
527} // end namespace clang