blob: f223fd0a6a91e14159bdf364863eac517f247953 [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"
Manuel Klimek47c245a2012-04-04 12:07:46 +000034
Chandler Carruth57f5fbe2014-04-21 22:55:36 +000035#define DEBUG_TYPE "clang-tooling"
36
Manuel Klimek47c245a2012-04-04 12:07:46 +000037namespace clang {
38namespace tooling {
39
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000040ToolAction::~ToolAction() {}
Peter Collingbournec689ee72013-11-06 20:12:45 +000041
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000042FrontendActionFactory::~FrontendActionFactory() {}
Manuel Klimek47c245a2012-04-04 12:07:46 +000043
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.
Benjamin Kramer407eb792015-10-09 13:03:25 +000049static clang::driver::Driver *newDriver(
50 clang::DiagnosticsEngine *Diagnostics, const char *BinaryName,
51 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000052 clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
Benjamin Kramer407eb792015-10-09 13:03:25 +000053 BinaryName, llvm::sys::getDefaultTargetTriple(), *Diagnostics, VFS);
Manuel Klimek47c245a2012-04-04 12:07:46 +000054 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.
Reid Kleckner898229a2013-06-14 17:17:23 +000061static const llvm::opt::ArgStringList *getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +000062 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();
Justin Bogneraab97922014-10-03 01:04:53 +000067 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000068 SmallString<256> error_msg;
Manuel Klimek47c245a2012-04-04 12:07:46 +000069 llvm::raw_svector_ostream error_stream(error_msg);
Hans Wennborgb212b342013-09-12 18:23:34 +000070 Jobs.Print(error_stream, "; ", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +000071 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
72 << error_stream.str();
Craig Topperccbc35e2014-05-20 04:51:16 +000073 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +000074 }
75
76 // The one job we find should be to invoke clang again.
David Blaikiec11bf802014-09-04 16:04:28 +000077 const clang::driver::Command &Cmd =
Justin Bogneraab97922014-10-03 01:04:53 +000078 cast<clang::driver::Command>(*Jobs.begin());
David Blaikiec11bf802014-09-04 16:04:28 +000079 if (StringRef(Cmd.getCreator().getName()) != "clang") {
Manuel Klimek47c245a2012-04-04 12:07:46 +000080 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
Craig Topperccbc35e2014-05-20 04:51:16 +000081 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +000082 }
83
David Blaikiec11bf802014-09-04 16:04:28 +000084 return &Cmd.getArguments();
Manuel Klimek47c245a2012-04-04 12:07:46 +000085}
86
87/// \brief Returns a clang build invocation initialized from the CC1 flags.
Manuel Klimekbea7dfb2015-03-28 00:42:36 +000088clang::CompilerInvocation *newInvocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +000089 clang::DiagnosticsEngine *Diagnostics,
Reid Kleckner898229a2013-06-14 17:17:23 +000090 const llvm::opt::ArgStringList &CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000091 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;
Nick Lewycky39dc9f82013-06-25 17:01:21 +000097 Invocation->getCodeGenOpts().DisableFree = false;
Peter Collingbournec0423b32014-03-02 23:37:26 +000098 Invocation->getDependencyOutputOpts() = DependencyOutputOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +000099 return Invocation;
100}
101
102bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000103 const Twine &FileName,
104 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
105 return runToolOnCodeWithArgs(ToolAction, Code, std::vector<std::string>(),
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000106 FileName, "clang-tool", PCHContainerOps);
Nico Weber077a53e2012-08-30 02:02:19 +0000107}
108
Peter Collingbournec689ee72013-11-06 20:12:45 +0000109static std::vector<std::string>
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000110getSyntaxOnlyToolArgs(const Twine &ToolName,
111 const std::vector<std::string> &ExtraArgs,
Peter Collingbournec689ee72013-11-06 20:12:45 +0000112 StringRef FileName) {
113 std::vector<std::string> Args;
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000114 Args.push_back(ToolName.str());
Peter Collingbournec689ee72013-11-06 20:12:45 +0000115 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
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000121bool runToolOnCodeWithArgs(
122 clang::FrontendAction *ToolAction, const Twine &Code,
123 const std::vector<std::string> &Args, const Twine &FileName,
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000124 const Twine &ToolName,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000125 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
126 const FileContentMappings &VirtualMappedFiles) {
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000127
Manuel Klimek47c245a2012-04-04 12:07:46 +0000128 SmallString<16> FileNameStorage;
129 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000130 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);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000135 llvm::IntrusiveRefCntPtr<FileManager> Files(
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000136 new FileManager(FileSystemOptions(), OverlayFileSystem));
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000137 ToolInvocation Invocation(getSyntaxOnlyToolArgs(ToolName, Args, FileNameRef),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000138 ToolAction, Files.get(), PCHContainerOps);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000139
140 SmallString<1024> CodeStorage;
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000141 InMemoryFileSystem->addFile(FileNameRef, 0,
142 llvm::MemoryBuffer::getMemBuffer(
143 Code.toNullTerminatedStringRef(CodeStorage)));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000144
145 for (auto &FilenameWithContent : VirtualMappedFiles) {
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000146 InMemoryFileSystem->addFile(
147 FilenameWithContent.first, 0,
148 llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000149 }
150
Manuel Klimek47c245a2012-04-04 12:07:46 +0000151 return Invocation.run();
152}
153
Manuel Klimek65fd0e12012-07-10 13:10:51 +0000154std::string getAbsolutePath(StringRef File) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000155 StringRef RelativePath(File);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000156 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimek47c245a2012-04-04 12:07:46 +0000157 if (RelativePath.startswith("./")) {
158 RelativePath = RelativePath.substr(strlen("./"));
159 }
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000160
161 SmallString<1024> AbsolutePath = RelativePath;
Rafael Espindolac0809172014-06-12 14:02:15 +0000162 std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000163 assert(!EC);
Rafael Espindola0b8e4a12013-08-10 04:25:53 +0000164 (void)EC;
Benjamin Kramer2d4d8cb2013-09-11 11:23:15 +0000165 llvm::sys::path::native(AbsolutePath);
166 return AbsolutePath.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000167}
168
Manuel Klimek9b30e2b2015-10-06 10:45:03 +0000169void 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
Peter Collingbournec689ee72013-11-06 20:12:45 +0000194namespace {
195
196class SingleFrontendActionFactory : public FrontendActionFactory {
197 FrontendAction *Action;
198
199public:
200 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
201
Craig Topperfb6b25b2014-03-15 04:29:04 +0000202 FrontendAction *create() override { return Action; }
Peter Collingbournec689ee72013-11-06 20:12:45 +0000203};
204
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000205}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000206
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000207ToolInvocation::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) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000212
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000213ToolInvocation::ToolInvocation(
214 std::vector<std::string> CommandLine, FrontendAction *FAction,
215 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000216 : CommandLine(std::move(CommandLine)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000217 Action(new SingleFrontendActionFactory(FAction)), OwnsAction(true),
218 Files(Files), PCHContainerOps(PCHContainerOps), DiagConsumer(nullptr) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000219
220ToolInvocation::~ToolInvocation() {
221 if (OwnsAction)
222 delete Action;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000223}
224
225void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi4de31652012-06-02 15:34:21 +0000226 SmallString<1024> PathStorage;
227 llvm::sys::path::native(FilePath, PathStorage);
228 MappedFileContents[PathStorage] = Content;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000229}
230
231bool ToolInvocation::run() {
232 std::vector<const char*> Argv;
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000233 for (const std::string &Str : CommandLine)
234 Argv.push_back(Str.c_str());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000235 const char *const BinaryName = Argv[0];
Douglas Gregor811db4e2012-10-23 22:26:28 +0000236 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000237 TextDiagnosticPrinter DiagnosticPrinter(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000238 llvm::errs(), &*DiagOpts);
239 DiagnosticsEngine Diagnostics(
Manuel Klimek64083012013-11-07 23:18:05 +0000240 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
241 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000242
Ahmed Charlesb8984322014-03-07 20:03:18 +0000243 const std::unique_ptr<clang::driver::Driver> Driver(
Benjamin Kramer407eb792015-10-09 13:03:25 +0000244 newDriver(&Diagnostics, BinaryName, Files->getVirtualFileSystem()));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000245 // Since the input might only be virtual, don't check whether it exists.
246 Driver->setCheckInputsExist(false);
Ahmed Charlesb8984322014-03-07 20:03:18 +0000247 const std::unique_ptr<clang::driver::Compilation> Compilation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000248 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
Reid Kleckner898229a2013-06-14 17:17:23 +0000249 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000250 &Diagnostics, Compilation.get());
Craig Topperccbc35e2014-05-20 04:51:16 +0000251 if (!CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000252 return false;
253 }
Ahmed Charlesb8984322014-03-07 20:03:18 +0000254 std::unique_ptr<clang::CompilerInvocation> Invocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000255 newInvocation(&Diagnostics, *CC1Args));
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000256 // FIXME: remove this when all users have migrated!
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000257 for (const auto &It : MappedFileContents) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000258 // Inject the code as the given file name into the preprocessor options.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000259 std::unique_ptr<llvm::MemoryBuffer> Input =
260 llvm::MemoryBuffer::getMemBuffer(It.getValue());
261 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
262 Input.release());
Peter Collingbournec689ee72013-11-06 20:12:45 +0000263 }
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000264 return runInvocation(BinaryName, Compilation.get(), Invocation.release(),
265 PCHContainerOps);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000266}
267
Manuel Klimek47c245a2012-04-04 12:07:46 +0000268bool ToolInvocation::runInvocation(
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000269 const char *BinaryName, clang::driver::Compilation *Compilation,
270 clang::CompilerInvocation *Invocation,
271 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000272 // Show the invocation, with -v.
273 if (Invocation->getHeaderSearchOpts().Verbose) {
274 llvm::errs() << "clang Invocation:\n";
Hans Wennborgb212b342013-09-12 18:23:34 +0000275 Compilation->getJobs().Print(llvm::errs(), "\n", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000276 llvm::errs() << "\n";
277 }
278
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000279 return Action->runInvocation(Invocation, Files, PCHContainerOps,
280 DiagConsumer);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000281}
282
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000283bool FrontendActionFactory::runInvocation(
284 CompilerInvocation *Invocation, FileManager *Files,
285 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
286 DiagnosticConsumer *DiagConsumer) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000287 // Create a compiler instance to handle the actual work.
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000288 clang::CompilerInstance Compiler(PCHContainerOps);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000289 Compiler.setInvocation(Invocation);
290 Compiler.setFileManager(Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000291
Peter Collingbournec689ee72013-11-06 20:12:45 +0000292 // 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
Ahmed Charlesb8984322014-03-07 20:03:18 +0000294 // pass it to an std::unique_ptr declared after the Compiler variable.
295 std::unique_ptr<FrontendAction> ScopedToolAction(create());
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000296
Alp Toker77273fc2014-05-16 13:45:29 +0000297 // Create the compiler's actual diagnostics engine.
Manuel Klimek64083012013-11-07 23:18:05 +0000298 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000299 if (!Compiler.hasDiagnostics())
300 return false;
301
302 Compiler.createSourceManager(*Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000303
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000304 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000305
Manuel Klimek3aad8552012-07-31 13:56:54 +0000306 Files->clearStatCaches();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000307 return Success;
308}
309
Manuel Klimek47c245a2012-04-04 12:07:46 +0000310ClangTool::ClangTool(const CompilationDatabase &Compilations,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000311 ArrayRef<std::string> SourcePaths,
312 std::shared_ptr<PCHContainerOperations> PCHContainerOps)
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000313 : Compilations(Compilations), SourcePaths(SourcePaths),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000314 PCHContainerOps(PCHContainerOps),
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000315 OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())),
316 InMemoryFileSystem(new vfs::InMemoryFileSystem),
317 Files(new FileManager(FileSystemOptions(), OverlayFileSystem)),
318 DiagConsumer(nullptr) {
319 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000320 appendArgumentsAdjuster(getClangStripOutputAdjuster());
321 appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000322}
323
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000324ClangTool::~ClangTool() {}
Manuel Klimek64083012013-11-07 23:18:05 +0000325
Manuel Klimek47c245a2012-04-04 12:07:46 +0000326void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
327 MappedFileContents.push_back(std::make_pair(FilePath, Content));
328}
329
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000330void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
331 if (ArgsAdjuster)
332 ArgsAdjuster = combineAdjusters(ArgsAdjuster, Adjuster);
333 else
334 ArgsAdjuster = Adjuster;
Manuel Klimekd91ac932013-06-04 14:44:44 +0000335}
336
337void ClangTool::clearArgumentsAdjusters() {
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000338 ArgsAdjuster = nullptr;
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000339}
340
Peter Collingbournec689ee72013-11-06 20:12:45 +0000341int ClangTool::run(ToolAction *Action) {
Alexander Kornienko8388d242012-06-04 19:02:59 +0000342 // 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 =
Rafael Espindola9678d272013-06-26 05:03:40 +0000351 llvm::sys::fs::getMainExecutable("clang_tool", &StaticSymbol);
Alexander Kornienko8388d242012-06-04 19:02:59 +0000352
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000353 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()));
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000357
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
Manuel Klimek47c245a2012-04-04 12:07:46 +0000367 bool ProcessingFailed = false;
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000368 for (const auto &SourcePath : SourcePaths) {
369 std::string File(getAbsolutePath(SourcePath));
370
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000371 // 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.
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000378 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;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000388 }
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000389 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.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000397 if (OverlayFileSystem->setCurrentWorkingDirectory(
398 CompileCommand.Directory))
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000399 llvm::report_fatal_error("Cannot chdir into \"" +
400 Twine(CompileCommand.Directory) + "\n!");
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000401
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
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000412 std::vector<std::string> CommandLine = CompileCommand.CommandLine;
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000413 if (ArgsAdjuster)
Alexander Kornienko857b10f2015-11-05 02:19:53 +0000414 CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000415 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"; });
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000420 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
421 PCHContainerOps);
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000422 Invocation.setDiagnosticConsumer(DiagConsumer);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000423
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000424 if (!Invocation.run()) {
425 // FIXME: Diagnostics should be used instead.
426 llvm::errs() << "Error while processing " << File << ".\n";
427 ProcessingFailed = true;
428 }
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000429 // Return to the initial directory to correctly resolve next file by
430 // relative path.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000431 if (OverlayFileSystem->setCurrentWorkingDirectory(InitialDirectory.c_str()))
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000432 llvm::report_fatal_error("Cannot chdir into \"" +
433 Twine(InitialDirectory) + "\n!");
Manuel Klimek47c245a2012-04-04 12:07:46 +0000434 }
435 }
436 return ProcessingFailed ? 1 : 0;
437}
438
Peter Collingbournec689ee72013-11-06 20:12:45 +0000439namespace {
440
441class ASTBuilderAction : public ToolAction {
David Blaikie39808ff2014-04-25 14:49:37 +0000442 std::vector<std::unique_ptr<ASTUnit>> &ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000443
444public:
David Blaikie39808ff2014-04-25 14:49:37 +0000445 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000446
Manuel Klimek64083012013-11-07 23:18:05 +0000447 bool runInvocation(CompilerInvocation *Invocation, FileManager *Files,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000448 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000449 DiagnosticConsumer *DiagConsumer) override {
David Blaikie103a2de2014-04-25 17:01:33 +0000450 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000451 Invocation, PCHContainerOps,
452 CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
453 DiagConsumer,
Benjamin Kramerbc632902015-10-06 14:45:20 +0000454 /*ShouldOwnClient=*/false),
455 Files);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000456 if (!AST)
457 return false;
458
David Blaikie39808ff2014-04-25 14:49:37 +0000459 ASTs.push_back(std::move(AST));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000460 return true;
461 }
462};
463
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000464}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000465
David Blaikie39808ff2014-04-25 14:49:37 +0000466int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000467 ASTBuilderAction Action(ASTs);
468 return run(&Action);
469}
470
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000471std::unique_ptr<ASTUnit>
472buildASTFromCode(const Twine &Code, const Twine &FileName,
473 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
474 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000475 "clang-tool", PCHContainerOps);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000476}
477
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000478std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
479 const Twine &Code, const std::vector<std::string> &Args,
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000480 const Twine &FileName, const Twine &ToolName,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000481 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000482 SmallString<16> FileNameStorage;
483 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
484
David Blaikie39808ff2014-04-25 14:49:37 +0000485 std::vector<std::unique_ptr<ASTUnit>> ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000486 ASTBuilderAction Action(ASTs);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000487 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);
Benjamin Kramerfa3dcf22015-10-06 15:04:13 +0000492 llvm::IntrusiveRefCntPtr<FileManager> Files(
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000493 new FileManager(FileSystemOptions(), OverlayFileSystem));
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000494 ToolInvocation Invocation(getSyntaxOnlyToolArgs(ToolName, Args, FileNameRef),
495 &Action, Files.get(), PCHContainerOps);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000496
497 SmallString<1024> CodeStorage;
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000498 InMemoryFileSystem->addFile(FileNameRef, 0,
499 llvm::MemoryBuffer::getMemBuffer(
500 Code.toNullTerminatedStringRef(CodeStorage)));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000501 if (!Invocation.run())
Craig Topperccbc35e2014-05-20 04:51:16 +0000502 return nullptr;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000503
504 assert(ASTs.size() == 1);
David Blaikie103a2de2014-04-25 17:01:33 +0000505 return std::move(ASTs[0]);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000506}
507
Manuel Klimek47c245a2012-04-04 12:07:46 +0000508} // end namespace tooling
509} // end namespace clang