blob: b44371c09b4e24c98be74852070fbc8e164cb640 [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
Peter Collingbournec689ee72013-11-06 20:12:45 +000040ToolAction::~ToolAction() {}
41
Manuel Klimek47c245a2012-04-04 12:07:46 +000042FrontendActionFactory::~FrontendActionFactory() {}
43
44// FIXME: This file contains structural duplication with other parts of the
45// code that sets up a compiler to run tools on it, and we should refactor
46// it to be based on the same framework.
47
48/// \brief Builds a clang driver initialized for running clang tools.
49static clang::driver::Driver *newDriver(clang::DiagnosticsEngine *Diagnostics,
50 const char *BinaryName) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000051 clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
Alp Toker1761f112014-05-15 22:26:36 +000052 BinaryName, llvm::sys::getDefaultTargetTriple(), *Diagnostics);
Manuel Klimek47c245a2012-04-04 12:07:46 +000053 CompilerDriver->setTitle("clang_based_tool");
54 return CompilerDriver;
55}
56
57/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
58///
59/// Returns NULL on error.
Reid Kleckner898229a2013-06-14 17:17:23 +000060static const llvm::opt::ArgStringList *getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +000061 clang::DiagnosticsEngine *Diagnostics,
62 clang::driver::Compilation *Compilation) {
63 // We expect to get back exactly one Command job, if we didn't something
64 // failed. Extract that job from the Compilation.
65 const clang::driver::JobList &Jobs = Compilation->getJobs();
Justin Bogneraab97922014-10-03 01:04:53 +000066 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000067 SmallString<256> error_msg;
Manuel Klimek47c245a2012-04-04 12:07:46 +000068 llvm::raw_svector_ostream error_stream(error_msg);
Hans Wennborgb212b342013-09-12 18:23:34 +000069 Jobs.Print(error_stream, "; ", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +000070 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
71 << error_stream.str();
Craig Topperccbc35e2014-05-20 04:51:16 +000072 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +000073 }
74
75 // The one job we find should be to invoke clang again.
David Blaikiec11bf802014-09-04 16:04:28 +000076 const clang::driver::Command &Cmd =
Justin Bogneraab97922014-10-03 01:04:53 +000077 cast<clang::driver::Command>(*Jobs.begin());
David Blaikiec11bf802014-09-04 16:04:28 +000078 if (StringRef(Cmd.getCreator().getName()) != "clang") {
Manuel Klimek47c245a2012-04-04 12:07:46 +000079 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
Craig Topperccbc35e2014-05-20 04:51:16 +000080 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +000081 }
82
David Blaikiec11bf802014-09-04 16:04:28 +000083 return &Cmd.getArguments();
Manuel Klimek47c245a2012-04-04 12:07:46 +000084}
85
86/// \brief Returns a clang build invocation initialized from the CC1 flags.
Manuel Klimekbea7dfb2015-03-28 00:42:36 +000087clang::CompilerInvocation *newInvocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +000088 clang::DiagnosticsEngine *Diagnostics,
Reid Kleckner898229a2013-06-14 17:17:23 +000089 const llvm::opt::ArgStringList &CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000090 assert(!CC1Args.empty() && "Must at least contain the program name!");
91 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
92 clang::CompilerInvocation::CreateFromArgs(
93 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
94 *Diagnostics);
95 Invocation->getFrontendOpts().DisableFree = false;
Nick Lewycky39dc9f82013-06-25 17:01:21 +000096 Invocation->getCodeGenOpts().DisableFree = false;
Peter Collingbournec0423b32014-03-02 23:37:26 +000097 Invocation->getDependencyOutputOpts() = DependencyOutputOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +000098 return Invocation;
99}
100
101bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000102 const Twine &FileName,
103 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
104 return runToolOnCodeWithArgs(ToolAction, Code, std::vector<std::string>(),
105 FileName, PCHContainerOps);
Nico Weber077a53e2012-08-30 02:02:19 +0000106}
107
Peter Collingbournec689ee72013-11-06 20:12:45 +0000108static std::vector<std::string>
109getSyntaxOnlyToolArgs(const std::vector<std::string> &ExtraArgs,
110 StringRef FileName) {
111 std::vector<std::string> Args;
112 Args.push_back("clang-tool");
113 Args.push_back("-fsyntax-only");
114 Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
115 Args.push_back(FileName.str());
116 return Args;
117}
118
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000119bool runToolOnCodeWithArgs(
120 clang::FrontendAction *ToolAction, const Twine &Code,
121 const std::vector<std::string> &Args, const Twine &FileName,
122 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
123 const FileContentMappings &VirtualMappedFiles) {
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000124
Manuel Klimek47c245a2012-04-04 12:07:46 +0000125 SmallString<16> FileNameStorage;
126 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000127 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
128 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
129 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
130 new vfs::InMemoryFileSystem);
131 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000132 llvm::IntrusiveRefCntPtr<FileManager> Files(
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000133 new FileManager(FileSystemOptions(), OverlayFileSystem));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000134 ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000135 ToolAction, Files.get(), PCHContainerOps);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000136
137 SmallString<1024> CodeStorage;
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000138 InMemoryFileSystem->addFile(FileNameRef, 0,
139 llvm::MemoryBuffer::getMemBuffer(
140 Code.toNullTerminatedStringRef(CodeStorage)));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000141
142 for (auto &FilenameWithContent : VirtualMappedFiles) {
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000143 InMemoryFileSystem->addFile(
144 FilenameWithContent.first, 0,
145 llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000146 }
147
Manuel Klimek47c245a2012-04-04 12:07:46 +0000148 return Invocation.run();
149}
150
Manuel Klimek65fd0e12012-07-10 13:10:51 +0000151std::string getAbsolutePath(StringRef File) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000152 StringRef RelativePath(File);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000153 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimek47c245a2012-04-04 12:07:46 +0000154 if (RelativePath.startswith("./")) {
155 RelativePath = RelativePath.substr(strlen("./"));
156 }
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000157
158 SmallString<1024> AbsolutePath = RelativePath;
Rafael Espindolac0809172014-06-12 14:02:15 +0000159 std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000160 assert(!EC);
Rafael Espindola0b8e4a12013-08-10 04:25:53 +0000161 (void)EC;
Benjamin Kramer2d4d8cb2013-09-11 11:23:15 +0000162 llvm::sys::path::native(AbsolutePath);
163 return AbsolutePath.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000164}
165
Manuel Klimek9b30e2b2015-10-06 10:45:03 +0000166void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
167 StringRef InvokedAs) {
168 if (!CommandLine.empty() && !InvokedAs.empty()) {
169 bool AlreadyHasTarget = false;
170 bool AlreadyHasMode = false;
171 // Skip CommandLine[0].
172 for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();
173 ++Token) {
174 StringRef TokenRef(*Token);
175 AlreadyHasTarget |=
176 (TokenRef == "-target" || TokenRef.startswith("-target="));
177 AlreadyHasMode |= (TokenRef == "--driver-mode" ||
178 TokenRef.startswith("--driver-mode="));
179 }
180 auto TargetMode =
181 clang::driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs);
182 if (!AlreadyHasMode && !TargetMode.second.empty()) {
183 CommandLine.insert(++CommandLine.begin(), TargetMode.second);
184 }
185 if (!AlreadyHasTarget && !TargetMode.first.empty()) {
186 CommandLine.insert(++CommandLine.begin(), {"-target", TargetMode.first});
187 }
188 }
189}
190
Peter Collingbournec689ee72013-11-06 20:12:45 +0000191namespace {
192
193class SingleFrontendActionFactory : public FrontendActionFactory {
194 FrontendAction *Action;
195
196public:
197 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
198
Craig Topperfb6b25b2014-03-15 04:29:04 +0000199 FrontendAction *create() override { return Action; }
Peter Collingbournec689ee72013-11-06 20:12:45 +0000200};
201
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000202}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000203
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000204ToolInvocation::ToolInvocation(
205 std::vector<std::string> CommandLine, ToolAction *Action,
206 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
207 : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false),
208 Files(Files), PCHContainerOps(PCHContainerOps), DiagConsumer(nullptr) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000209
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000210ToolInvocation::ToolInvocation(
211 std::vector<std::string> CommandLine, FrontendAction *FAction,
212 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000213 : CommandLine(std::move(CommandLine)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000214 Action(new SingleFrontendActionFactory(FAction)), OwnsAction(true),
215 Files(Files), PCHContainerOps(PCHContainerOps), DiagConsumer(nullptr) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000216
217ToolInvocation::~ToolInvocation() {
218 if (OwnsAction)
219 delete Action;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000220}
221
222void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi4de31652012-06-02 15:34:21 +0000223 SmallString<1024> PathStorage;
224 llvm::sys::path::native(FilePath, PathStorage);
225 MappedFileContents[PathStorage] = Content;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000226}
227
228bool ToolInvocation::run() {
229 std::vector<const char*> Argv;
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000230 for (const std::string &Str : CommandLine)
231 Argv.push_back(Str.c_str());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000232 const char *const BinaryName = Argv[0];
Douglas Gregor811db4e2012-10-23 22:26:28 +0000233 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000234 TextDiagnosticPrinter DiagnosticPrinter(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000235 llvm::errs(), &*DiagOpts);
236 DiagnosticsEngine Diagnostics(
Manuel Klimek64083012013-11-07 23:18:05 +0000237 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
238 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000239
Ahmed Charlesb8984322014-03-07 20:03:18 +0000240 const std::unique_ptr<clang::driver::Driver> Driver(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000241 newDriver(&Diagnostics, BinaryName));
242 // Since the input might only be virtual, don't check whether it exists.
243 Driver->setCheckInputsExist(false);
Ahmed Charlesb8984322014-03-07 20:03:18 +0000244 const std::unique_ptr<clang::driver::Compilation> Compilation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000245 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
Reid Kleckner898229a2013-06-14 17:17:23 +0000246 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000247 &Diagnostics, Compilation.get());
Craig Topperccbc35e2014-05-20 04:51:16 +0000248 if (!CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000249 return false;
250 }
Ahmed Charlesb8984322014-03-07 20:03:18 +0000251 std::unique_ptr<clang::CompilerInvocation> Invocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000252 newInvocation(&Diagnostics, *CC1Args));
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000253 // FIXME: remove this when all users have migrated!
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000254 for (const auto &It : MappedFileContents) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000255 // Inject the code as the given file name into the preprocessor options.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000256 std::unique_ptr<llvm::MemoryBuffer> Input =
257 llvm::MemoryBuffer::getMemBuffer(It.getValue());
258 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
259 Input.release());
Peter Collingbournec689ee72013-11-06 20:12:45 +0000260 }
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000261 return runInvocation(BinaryName, Compilation.get(), Invocation.release(),
262 PCHContainerOps);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000263}
264
Manuel Klimek47c245a2012-04-04 12:07:46 +0000265bool ToolInvocation::runInvocation(
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000266 const char *BinaryName, clang::driver::Compilation *Compilation,
267 clang::CompilerInvocation *Invocation,
268 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000269 // Show the invocation, with -v.
270 if (Invocation->getHeaderSearchOpts().Verbose) {
271 llvm::errs() << "clang Invocation:\n";
Hans Wennborgb212b342013-09-12 18:23:34 +0000272 Compilation->getJobs().Print(llvm::errs(), "\n", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000273 llvm::errs() << "\n";
274 }
275
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000276 return Action->runInvocation(Invocation, Files, PCHContainerOps,
277 DiagConsumer);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000278}
279
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000280bool FrontendActionFactory::runInvocation(
281 CompilerInvocation *Invocation, FileManager *Files,
282 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
283 DiagnosticConsumer *DiagConsumer) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000284 // Create a compiler instance to handle the actual work.
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000285 clang::CompilerInstance Compiler(PCHContainerOps);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000286 Compiler.setInvocation(Invocation);
287 Compiler.setFileManager(Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000288
Peter Collingbournec689ee72013-11-06 20:12:45 +0000289 // The FrontendAction can have lifetime requirements for Compiler or its
290 // members, and we need to ensure it's deleted earlier than Compiler. So we
Ahmed Charlesb8984322014-03-07 20:03:18 +0000291 // pass it to an std::unique_ptr declared after the Compiler variable.
292 std::unique_ptr<FrontendAction> ScopedToolAction(create());
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000293
Alp Toker77273fc2014-05-16 13:45:29 +0000294 // Create the compiler's actual diagnostics engine.
Manuel Klimek64083012013-11-07 23:18:05 +0000295 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000296 if (!Compiler.hasDiagnostics())
297 return false;
298
299 Compiler.createSourceManager(*Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000300
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000301 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000302
Manuel Klimek3aad8552012-07-31 13:56:54 +0000303 Files->clearStatCaches();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000304 return Success;
305}
306
Manuel Klimek47c245a2012-04-04 12:07:46 +0000307ClangTool::ClangTool(const CompilationDatabase &Compilations,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000308 ArrayRef<std::string> SourcePaths,
309 std::shared_ptr<PCHContainerOperations> PCHContainerOps)
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000310 : Compilations(Compilations), SourcePaths(SourcePaths),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000311 PCHContainerOps(PCHContainerOps),
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000312 OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())),
313 InMemoryFileSystem(new vfs::InMemoryFileSystem),
314 Files(new FileManager(FileSystemOptions(), OverlayFileSystem)),
315 DiagConsumer(nullptr) {
316 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000317 appendArgumentsAdjuster(getClangStripOutputAdjuster());
318 appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000319}
320
Benjamin Kramer90e0fd82014-09-24 11:47:42 +0000321ClangTool::~ClangTool() {}
Manuel Klimek64083012013-11-07 23:18:05 +0000322
Manuel Klimek47c245a2012-04-04 12:07:46 +0000323void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
324 MappedFileContents.push_back(std::make_pair(FilePath, Content));
325}
326
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000327void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
328 if (ArgsAdjuster)
329 ArgsAdjuster = combineAdjusters(ArgsAdjuster, Adjuster);
330 else
331 ArgsAdjuster = Adjuster;
Manuel Klimekd91ac932013-06-04 14:44:44 +0000332}
333
334void ClangTool::clearArgumentsAdjusters() {
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000335 ArgsAdjuster = nullptr;
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000336}
337
Peter Collingbournec689ee72013-11-06 20:12:45 +0000338int ClangTool::run(ToolAction *Action) {
Alexander Kornienko8388d242012-06-04 19:02:59 +0000339 // Exists solely for the purpose of lookup of the resource path.
340 // This just needs to be some symbol in the binary.
341 static int StaticSymbol;
342 // The driver detects the builtin header path based on the path of the
343 // executable.
344 // FIXME: On linux, GetMainExecutable is independent of the value of the
345 // first argument, thus allowing ClangTool and runToolOnCode to just
346 // pass in made-up names here. Make sure this works on other platforms.
347 std::string MainExecutable =
Rafael Espindola9678d272013-06-26 05:03:40 +0000348 llvm::sys::fs::getMainExecutable("clang_tool", &StaticSymbol);
Alexander Kornienko8388d242012-06-04 19:02:59 +0000349
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000350 llvm::SmallString<128> InitialDirectory;
351 if (std::error_code EC = llvm::sys::fs::current_path(InitialDirectory))
352 llvm::report_fatal_error("Cannot detect current path: " +
353 Twine(EC.message()));
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000354
355 // First insert all absolute paths into the in-memory VFS. These are global
356 // for all compile commands.
357 if (SeenWorkingDirectories.insert("/").second)
358 for (const auto &MappedFile : MappedFileContents)
359 if (llvm::sys::path::is_absolute(MappedFile.first))
360 InMemoryFileSystem->addFile(
361 MappedFile.first, 0,
362 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
363
Manuel Klimek47c245a2012-04-04 12:07:46 +0000364 bool ProcessingFailed = false;
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000365 for (const auto &SourcePath : SourcePaths) {
366 std::string File(getAbsolutePath(SourcePath));
367
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000368 // Currently implementations of CompilationDatabase::getCompileCommands can
369 // change the state of the file system (e.g. prepare generated headers), so
370 // this method needs to run right before we invoke the tool, as the next
371 // file may require a different (incompatible) state of the file system.
372 //
373 // FIXME: Make the compilation database interface more explicit about the
374 // requirements to the order of invocation of its members.
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000375 std::vector<CompileCommand> CompileCommandsForFile =
376 Compilations.getCompileCommands(File);
377 if (CompileCommandsForFile.empty()) {
378 // FIXME: There are two use cases here: doing a fuzzy
379 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
380 // about the .cc files that were not found, and the use case where I
381 // specify all files I want to run over explicitly, where this should
382 // be an error. We'll want to add an option for this.
383 llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
384 continue;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000385 }
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000386 for (CompileCommand &CompileCommand : CompileCommandsForFile) {
387 // FIXME: chdir is thread hostile; on the other hand, creating the same
388 // behavior as chdir is complex: chdir resolves the path once, thus
389 // guaranteeing that all subsequent relative path operations work
390 // on the same path the original chdir resulted in. This makes a
391 // difference for example on network filesystems, where symlinks might be
392 // switched during runtime of the tool. Fixing this depends on having a
393 // file system abstraction that allows openat() style interactions.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000394 if (OverlayFileSystem->setCurrentWorkingDirectory(
395 CompileCommand.Directory))
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000396 llvm::report_fatal_error("Cannot chdir into \"" +
397 Twine(CompileCommand.Directory) + "\n!");
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000398
399 // Now fill the in-memory VFS with the relative file mappings so it will
400 // have the correct relative paths. We never remove mappings but that
401 // should be fine.
402 if (SeenWorkingDirectories.insert(CompileCommand.Directory).second)
403 for (const auto &MappedFile : MappedFileContents)
404 if (!llvm::sys::path::is_absolute(MappedFile.first))
405 InMemoryFileSystem->addFile(
406 MappedFile.first, 0,
407 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
408
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000409 std::vector<std::string> CommandLine = CompileCommand.CommandLine;
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000410 if (ArgsAdjuster)
411 CommandLine = ArgsAdjuster(CommandLine);
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000412 assert(!CommandLine.empty());
413 CommandLine[0] = MainExecutable;
414 // FIXME: We need a callback mechanism for the tool writer to output a
415 // customized message for each file.
416 DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000417 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
418 PCHContainerOps);
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000419 Invocation.setDiagnosticConsumer(DiagConsumer);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000420
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000421 if (!Invocation.run()) {
422 // FIXME: Diagnostics should be used instead.
423 llvm::errs() << "Error while processing " << File << ".\n";
424 ProcessingFailed = true;
425 }
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000426 // Return to the initial directory to correctly resolve next file by
427 // relative path.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000428 if (OverlayFileSystem->setCurrentWorkingDirectory(InitialDirectory.c_str()))
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000429 llvm::report_fatal_error("Cannot chdir into \"" +
430 Twine(InitialDirectory) + "\n!");
Manuel Klimek47c245a2012-04-04 12:07:46 +0000431 }
432 }
433 return ProcessingFailed ? 1 : 0;
434}
435
Peter Collingbournec689ee72013-11-06 20:12:45 +0000436namespace {
437
438class ASTBuilderAction : public ToolAction {
David Blaikie39808ff2014-04-25 14:49:37 +0000439 std::vector<std::unique_ptr<ASTUnit>> &ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000440
441public:
David Blaikie39808ff2014-04-25 14:49:37 +0000442 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000443
Manuel Klimek64083012013-11-07 23:18:05 +0000444 bool runInvocation(CompilerInvocation *Invocation, FileManager *Files,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000445 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000446 DiagnosticConsumer *DiagConsumer) override {
David Blaikie103a2de2014-04-25 17:01:33 +0000447 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000448 Invocation, PCHContainerOps,
449 CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
450 DiagConsumer,
Benjamin Kramerbc632902015-10-06 14:45:20 +0000451 /*ShouldOwnClient=*/false),
452 Files);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000453 if (!AST)
454 return false;
455
David Blaikie39808ff2014-04-25 14:49:37 +0000456 ASTs.push_back(std::move(AST));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000457 return true;
458 }
459};
460
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000461}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000462
David Blaikie39808ff2014-04-25 14:49:37 +0000463int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000464 ASTBuilderAction Action(ASTs);
465 return run(&Action);
466}
467
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000468std::unique_ptr<ASTUnit>
469buildASTFromCode(const Twine &Code, const Twine &FileName,
470 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
471 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
472 PCHContainerOps);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000473}
474
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000475std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
476 const Twine &Code, const std::vector<std::string> &Args,
477 const Twine &FileName,
478 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000479 SmallString<16> FileNameStorage;
480 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
481
David Blaikie39808ff2014-04-25 14:49:37 +0000482 std::vector<std::unique_ptr<ASTUnit>> ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000483 ASTBuilderAction Action(ASTs);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000484 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
485 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
486 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
487 new vfs::InMemoryFileSystem);
488 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Benjamin Kramerfa3dcf22015-10-06 15:04:13 +0000489 llvm::IntrusiveRefCntPtr<FileManager> Files(
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000490 new FileManager(FileSystemOptions(), OverlayFileSystem));
Craig Topperccbc35e2014-05-20 04:51:16 +0000491 ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), &Action,
Benjamin Kramerfa3dcf22015-10-06 15:04:13 +0000492 Files.get(), PCHContainerOps);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000493
494 SmallString<1024> CodeStorage;
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000495 InMemoryFileSystem->addFile(FileNameRef, 0,
496 llvm::MemoryBuffer::getMemBuffer(
497 Code.toNullTerminatedStringRef(CodeStorage)));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000498 if (!Invocation.run())
Craig Topperccbc35e2014-05-20 04:51:16 +0000499 return nullptr;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000500
501 assert(ASTs.size() == 1);
David Blaikie103a2de2014-04-25 17:01:33 +0000502 return std::move(ASTs[0]);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000503}
504
Manuel Klimek47c245a2012-04-04 12:07:46 +0000505} // end namespace tooling
506} // end namespace clang