blob: 8dee24dcff4fca17802529e32a36ab314308bd50 [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) {
Benjamin Kramer7320b992016-06-15 14:20:56 +000053 clang::driver::Driver *CompilerDriver =
54 new clang::driver::Driver(BinaryName, llvm::sys::getDefaultTargetTriple(),
55 *Diagnostics, std::move(VFS));
Manuel Klimek47c245a2012-04-04 12:07:46 +000056 CompilerDriver->setTitle("clang_based_tool");
57 return CompilerDriver;
58}
59
60/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
61///
62/// Returns NULL on error.
Reid Kleckner898229a2013-06-14 17:17:23 +000063static const llvm::opt::ArgStringList *getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +000064 clang::DiagnosticsEngine *Diagnostics,
65 clang::driver::Compilation *Compilation) {
66 // We expect to get back exactly one Command job, if we didn't something
67 // failed. Extract that job from the Compilation.
68 const clang::driver::JobList &Jobs = Compilation->getJobs();
Justin Bogneraab97922014-10-03 01:04:53 +000069 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000070 SmallString<256> error_msg;
Manuel Klimek47c245a2012-04-04 12:07:46 +000071 llvm::raw_svector_ostream error_stream(error_msg);
Hans Wennborgb212b342013-09-12 18:23:34 +000072 Jobs.Print(error_stream, "; ", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +000073 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
74 << error_stream.str();
Craig Topperccbc35e2014-05-20 04:51:16 +000075 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +000076 }
77
78 // The one job we find should be to invoke clang again.
David Blaikiec11bf802014-09-04 16:04:28 +000079 const clang::driver::Command &Cmd =
Justin Bogneraab97922014-10-03 01:04:53 +000080 cast<clang::driver::Command>(*Jobs.begin());
David Blaikiec11bf802014-09-04 16:04:28 +000081 if (StringRef(Cmd.getCreator().getName()) != "clang") {
Manuel Klimek47c245a2012-04-04 12:07:46 +000082 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
Craig Topperccbc35e2014-05-20 04:51:16 +000083 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +000084 }
85
David Blaikiec11bf802014-09-04 16:04:28 +000086 return &Cmd.getArguments();
Manuel Klimek47c245a2012-04-04 12:07:46 +000087}
88
89/// \brief Returns a clang build invocation initialized from the CC1 flags.
Manuel Klimekbea7dfb2015-03-28 00:42:36 +000090clang::CompilerInvocation *newInvocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +000091 clang::DiagnosticsEngine *Diagnostics,
Reid Kleckner898229a2013-06-14 17:17:23 +000092 const llvm::opt::ArgStringList &CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000093 assert(!CC1Args.empty() && "Must at least contain the program name!");
94 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
95 clang::CompilerInvocation::CreateFromArgs(
96 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
97 *Diagnostics);
98 Invocation->getFrontendOpts().DisableFree = false;
Nick Lewycky39dc9f82013-06-25 17:01:21 +000099 Invocation->getCodeGenOpts().DisableFree = false;
Peter Collingbournec0423b32014-03-02 23:37:26 +0000100 Invocation->getDependencyOutputOpts() = DependencyOutputOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000101 return Invocation;
102}
103
104bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000105 const Twine &FileName,
106 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
107 return runToolOnCodeWithArgs(ToolAction, Code, std::vector<std::string>(),
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000108 FileName, "clang-tool",
109 std::move(PCHContainerOps));
Nico Weber077a53e2012-08-30 02:02:19 +0000110}
111
Peter Collingbournec689ee72013-11-06 20:12:45 +0000112static std::vector<std::string>
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000113getSyntaxOnlyToolArgs(const Twine &ToolName,
114 const std::vector<std::string> &ExtraArgs,
Peter Collingbournec689ee72013-11-06 20:12:45 +0000115 StringRef FileName) {
116 std::vector<std::string> Args;
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000117 Args.push_back(ToolName.str());
Peter Collingbournec689ee72013-11-06 20:12:45 +0000118 Args.push_back("-fsyntax-only");
119 Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
120 Args.push_back(FileName.str());
121 return Args;
122}
123
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000124bool runToolOnCodeWithArgs(
125 clang::FrontendAction *ToolAction, const Twine &Code,
126 const std::vector<std::string> &Args, const Twine &FileName,
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000127 const Twine &ToolName,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000128 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
129 const FileContentMappings &VirtualMappedFiles) {
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000130
Manuel Klimek47c245a2012-04-04 12:07:46 +0000131 SmallString<16> FileNameStorage;
132 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000133 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
134 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
135 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
136 new vfs::InMemoryFileSystem);
137 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000138 llvm::IntrusiveRefCntPtr<FileManager> Files(
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000139 new FileManager(FileSystemOptions(), OverlayFileSystem));
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000140 ToolInvocation Invocation(getSyntaxOnlyToolArgs(ToolName, Args, FileNameRef),
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000141 ToolAction, Files.get(),
142 std::move(PCHContainerOps));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000143
144 SmallString<1024> CodeStorage;
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000145 InMemoryFileSystem->addFile(FileNameRef, 0,
146 llvm::MemoryBuffer::getMemBuffer(
147 Code.toNullTerminatedStringRef(CodeStorage)));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000148
149 for (auto &FilenameWithContent : VirtualMappedFiles) {
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000150 InMemoryFileSystem->addFile(
151 FilenameWithContent.first, 0,
152 llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000153 }
154
Manuel Klimek47c245a2012-04-04 12:07:46 +0000155 return Invocation.run();
156}
157
Manuel Klimek65fd0e12012-07-10 13:10:51 +0000158std::string getAbsolutePath(StringRef File) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000159 StringRef RelativePath(File);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000160 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimek47c245a2012-04-04 12:07:46 +0000161 if (RelativePath.startswith("./")) {
162 RelativePath = RelativePath.substr(strlen("./"));
163 }
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000164
165 SmallString<1024> AbsolutePath = RelativePath;
Rafael Espindolac0809172014-06-12 14:02:15 +0000166 std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000167 assert(!EC);
Rafael Espindola0b8e4a12013-08-10 04:25:53 +0000168 (void)EC;
Benjamin Kramer2d4d8cb2013-09-11 11:23:15 +0000169 llvm::sys::path::native(AbsolutePath);
170 return AbsolutePath.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000171}
172
Manuel Klimek9b30e2b2015-10-06 10:45:03 +0000173void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
174 StringRef InvokedAs) {
175 if (!CommandLine.empty() && !InvokedAs.empty()) {
176 bool AlreadyHasTarget = false;
177 bool AlreadyHasMode = false;
178 // Skip CommandLine[0].
179 for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();
180 ++Token) {
181 StringRef TokenRef(*Token);
182 AlreadyHasTarget |=
183 (TokenRef == "-target" || TokenRef.startswith("-target="));
184 AlreadyHasMode |= (TokenRef == "--driver-mode" ||
185 TokenRef.startswith("--driver-mode="));
186 }
187 auto TargetMode =
188 clang::driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs);
189 if (!AlreadyHasMode && !TargetMode.second.empty()) {
190 CommandLine.insert(++CommandLine.begin(), TargetMode.second);
191 }
192 if (!AlreadyHasTarget && !TargetMode.first.empty()) {
193 CommandLine.insert(++CommandLine.begin(), {"-target", TargetMode.first});
194 }
195 }
196}
197
Peter Collingbournec689ee72013-11-06 20:12:45 +0000198namespace {
199
200class SingleFrontendActionFactory : public FrontendActionFactory {
201 FrontendAction *Action;
202
203public:
204 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
205
Craig Topperfb6b25b2014-03-15 04:29:04 +0000206 FrontendAction *create() override { return Action; }
Peter Collingbournec689ee72013-11-06 20:12:45 +0000207};
208
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000209}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000210
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000211ToolInvocation::ToolInvocation(
212 std::vector<std::string> CommandLine, ToolAction *Action,
213 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
214 : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false),
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000215 Files(Files), PCHContainerOps(std::move(PCHContainerOps)),
216 DiagConsumer(nullptr) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000217
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000218ToolInvocation::ToolInvocation(
219 std::vector<std::string> CommandLine, FrontendAction *FAction,
220 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000221 : CommandLine(std::move(CommandLine)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000222 Action(new SingleFrontendActionFactory(FAction)), OwnsAction(true),
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000223 Files(Files), PCHContainerOps(std::move(PCHContainerOps)),
224 DiagConsumer(nullptr) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000225
226ToolInvocation::~ToolInvocation() {
227 if (OwnsAction)
228 delete Action;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000229}
230
231void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi4de31652012-06-02 15:34:21 +0000232 SmallString<1024> PathStorage;
233 llvm::sys::path::native(FilePath, PathStorage);
234 MappedFileContents[PathStorage] = Content;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000235}
236
237bool ToolInvocation::run() {
238 std::vector<const char*> Argv;
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000239 for (const std::string &Str : CommandLine)
240 Argv.push_back(Str.c_str());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000241 const char *const BinaryName = Argv[0];
Douglas Gregor811db4e2012-10-23 22:26:28 +0000242 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000243 TextDiagnosticPrinter DiagnosticPrinter(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000244 llvm::errs(), &*DiagOpts);
245 DiagnosticsEngine Diagnostics(
Manuel Klimek64083012013-11-07 23:18:05 +0000246 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
247 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000248
Ahmed Charlesb8984322014-03-07 20:03:18 +0000249 const std::unique_ptr<clang::driver::Driver> Driver(
Benjamin Kramer407eb792015-10-09 13:03:25 +0000250 newDriver(&Diagnostics, BinaryName, Files->getVirtualFileSystem()));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000251 // Since the input might only be virtual, don't check whether it exists.
252 Driver->setCheckInputsExist(false);
Ahmed Charlesb8984322014-03-07 20:03:18 +0000253 const std::unique_ptr<clang::driver::Compilation> Compilation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000254 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
Reid Kleckner898229a2013-06-14 17:17:23 +0000255 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000256 &Diagnostics, Compilation.get());
Craig Topperccbc35e2014-05-20 04:51:16 +0000257 if (!CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000258 return false;
259 }
Ahmed Charlesb8984322014-03-07 20:03:18 +0000260 std::unique_ptr<clang::CompilerInvocation> Invocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000261 newInvocation(&Diagnostics, *CC1Args));
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000262 // FIXME: remove this when all users have migrated!
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000263 for (const auto &It : MappedFileContents) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000264 // Inject the code as the given file name into the preprocessor options.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000265 std::unique_ptr<llvm::MemoryBuffer> Input =
266 llvm::MemoryBuffer::getMemBuffer(It.getValue());
267 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
268 Input.release());
Peter Collingbournec689ee72013-11-06 20:12:45 +0000269 }
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000270 return runInvocation(BinaryName, Compilation.get(), Invocation.release(),
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000271 std::move(PCHContainerOps));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000272}
273
Manuel Klimek47c245a2012-04-04 12:07:46 +0000274bool ToolInvocation::runInvocation(
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000275 const char *BinaryName, clang::driver::Compilation *Compilation,
276 clang::CompilerInvocation *Invocation,
277 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000278 // Show the invocation, with -v.
279 if (Invocation->getHeaderSearchOpts().Verbose) {
280 llvm::errs() << "clang Invocation:\n";
Hans Wennborgb212b342013-09-12 18:23:34 +0000281 Compilation->getJobs().Print(llvm::errs(), "\n", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000282 llvm::errs() << "\n";
283 }
284
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000285 return Action->runInvocation(Invocation, Files, std::move(PCHContainerOps),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000286 DiagConsumer);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000287}
288
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000289bool FrontendActionFactory::runInvocation(
290 CompilerInvocation *Invocation, FileManager *Files,
291 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
292 DiagnosticConsumer *DiagConsumer) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000293 // Create a compiler instance to handle the actual work.
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000294 clang::CompilerInstance Compiler(std::move(PCHContainerOps));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000295 Compiler.setInvocation(Invocation);
296 Compiler.setFileManager(Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000297
Peter Collingbournec689ee72013-11-06 20:12:45 +0000298 // The FrontendAction can have lifetime requirements for Compiler or its
299 // members, and we need to ensure it's deleted earlier than Compiler. So we
Ahmed Charlesb8984322014-03-07 20:03:18 +0000300 // pass it to an std::unique_ptr declared after the Compiler variable.
301 std::unique_ptr<FrontendAction> ScopedToolAction(create());
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000302
Alp Toker77273fc2014-05-16 13:45:29 +0000303 // Create the compiler's actual diagnostics engine.
Manuel Klimek64083012013-11-07 23:18:05 +0000304 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000305 if (!Compiler.hasDiagnostics())
306 return false;
307
308 Compiler.createSourceManager(*Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000309
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000310 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000311
Manuel Klimek3aad8552012-07-31 13:56:54 +0000312 Files->clearStatCaches();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000313 return Success;
314}
315
Manuel Klimek47c245a2012-04-04 12:07:46 +0000316ClangTool::ClangTool(const CompilationDatabase &Compilations,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000317 ArrayRef<std::string> SourcePaths,
318 std::shared_ptr<PCHContainerOperations> PCHContainerOps)
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000319 : Compilations(Compilations), SourcePaths(SourcePaths),
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000320 PCHContainerOps(std::move(PCHContainerOps)),
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000321 OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())),
322 InMemoryFileSystem(new vfs::InMemoryFileSystem),
323 Files(new FileManager(FileSystemOptions(), OverlayFileSystem)),
324 DiagConsumer(nullptr) {
325 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000326 appendArgumentsAdjuster(getClangStripOutputAdjuster());
327 appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000328}
329
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000330ClangTool::~ClangTool() {}
Manuel Klimek64083012013-11-07 23:18:05 +0000331
Manuel Klimek47c245a2012-04-04 12:07:46 +0000332void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
333 MappedFileContents.push_back(std::make_pair(FilePath, Content));
334}
335
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000336void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
337 if (ArgsAdjuster)
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000338 ArgsAdjuster =
339 combineAdjusters(std::move(ArgsAdjuster), std::move(Adjuster));
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000340 else
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000341 ArgsAdjuster = std::move(Adjuster);
Manuel Klimekd91ac932013-06-04 14:44:44 +0000342}
343
344void ClangTool::clearArgumentsAdjusters() {
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000345 ArgsAdjuster = nullptr;
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000346}
347
Benjamin Kramerb5737c12016-04-21 10:18:18 +0000348static void injectResourceDir(CommandLineArguments &Args, const char *Argv0,
349 void *MainAddr) {
350 // Allow users to override the resource dir.
351 for (StringRef Arg : Args)
352 if (Arg.startswith("-resource-dir"))
353 return;
354
355 // If there's no override in place add our resource dir.
356 Args.push_back("-resource-dir=" +
357 CompilerInvocation::GetResourcesPath(Argv0, MainAddr));
358}
359
Peter Collingbournec689ee72013-11-06 20:12:45 +0000360int ClangTool::run(ToolAction *Action) {
Alexander Kornienko8388d242012-06-04 19:02:59 +0000361 // Exists solely for the purpose of lookup of the resource path.
362 // This just needs to be some symbol in the binary.
363 static int StaticSymbol;
Alexander Kornienko8388d242012-06-04 19:02:59 +0000364
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000365 llvm::SmallString<128> InitialDirectory;
366 if (std::error_code EC = llvm::sys::fs::current_path(InitialDirectory))
367 llvm::report_fatal_error("Cannot detect current path: " +
368 Twine(EC.message()));
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000369
370 // First insert all absolute paths into the in-memory VFS. These are global
371 // for all compile commands.
372 if (SeenWorkingDirectories.insert("/").second)
373 for (const auto &MappedFile : MappedFileContents)
374 if (llvm::sys::path::is_absolute(MappedFile.first))
375 InMemoryFileSystem->addFile(
376 MappedFile.first, 0,
377 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
378
Manuel Klimek47c245a2012-04-04 12:07:46 +0000379 bool ProcessingFailed = false;
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000380 for (const auto &SourcePath : SourcePaths) {
381 std::string File(getAbsolutePath(SourcePath));
382
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000383 // Currently implementations of CompilationDatabase::getCompileCommands can
384 // change the state of the file system (e.g. prepare generated headers), so
385 // this method needs to run right before we invoke the tool, as the next
386 // file may require a different (incompatible) state of the file system.
387 //
388 // FIXME: Make the compilation database interface more explicit about the
389 // requirements to the order of invocation of its members.
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000390 std::vector<CompileCommand> CompileCommandsForFile =
391 Compilations.getCompileCommands(File);
392 if (CompileCommandsForFile.empty()) {
393 // FIXME: There are two use cases here: doing a fuzzy
394 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
395 // about the .cc files that were not found, and the use case where I
396 // specify all files I want to run over explicitly, where this should
397 // be an error. We'll want to add an option for this.
398 llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
399 continue;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000400 }
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000401 for (CompileCommand &CompileCommand : CompileCommandsForFile) {
402 // FIXME: chdir is thread hostile; on the other hand, creating the same
403 // behavior as chdir is complex: chdir resolves the path once, thus
404 // guaranteeing that all subsequent relative path operations work
405 // on the same path the original chdir resulted in. This makes a
406 // difference for example on network filesystems, where symlinks might be
407 // switched during runtime of the tool. Fixing this depends on having a
408 // file system abstraction that allows openat() style interactions.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000409 if (OverlayFileSystem->setCurrentWorkingDirectory(
410 CompileCommand.Directory))
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000411 llvm::report_fatal_error("Cannot chdir into \"" +
412 Twine(CompileCommand.Directory) + "\n!");
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000413
414 // Now fill the in-memory VFS with the relative file mappings so it will
415 // have the correct relative paths. We never remove mappings but that
416 // should be fine.
417 if (SeenWorkingDirectories.insert(CompileCommand.Directory).second)
418 for (const auto &MappedFile : MappedFileContents)
419 if (!llvm::sys::path::is_absolute(MappedFile.first))
420 InMemoryFileSystem->addFile(
421 MappedFile.first, 0,
422 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
423
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000424 std::vector<std::string> CommandLine = CompileCommand.CommandLine;
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000425 if (ArgsAdjuster)
Alexander Kornienko857b10f2015-11-05 02:19:53 +0000426 CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000427 assert(!CommandLine.empty());
Benjamin Kramerb5737c12016-04-21 10:18:18 +0000428
429 // Add the resource dir based on the binary of this tool. argv[0] in the
430 // compilation database may refer to a different compiler and we want to
431 // pick up the very same standard library that compiler is using. The
432 // builtin headers in the resource dir need to match the exact clang
433 // version the tool is using.
434 // FIXME: On linux, GetMainExecutable is independent of the value of the
435 // first argument, thus allowing ClangTool and runToolOnCode to just
436 // pass in made-up names here. Make sure this works on other platforms.
437 injectResourceDir(CommandLine, "clang_tool", &StaticSymbol);
438
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000439 // FIXME: We need a callback mechanism for the tool writer to output a
440 // customized message for each file.
441 DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000442 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
443 PCHContainerOps);
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000444 Invocation.setDiagnosticConsumer(DiagConsumer);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000445
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000446 if (!Invocation.run()) {
447 // FIXME: Diagnostics should be used instead.
448 llvm::errs() << "Error while processing " << File << ".\n";
449 ProcessingFailed = true;
450 }
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000451 // Return to the initial directory to correctly resolve next file by
452 // relative path.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000453 if (OverlayFileSystem->setCurrentWorkingDirectory(InitialDirectory.c_str()))
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000454 llvm::report_fatal_error("Cannot chdir into \"" +
455 Twine(InitialDirectory) + "\n!");
Manuel Klimek47c245a2012-04-04 12:07:46 +0000456 }
457 }
458 return ProcessingFailed ? 1 : 0;
459}
460
Peter Collingbournec689ee72013-11-06 20:12:45 +0000461namespace {
462
463class ASTBuilderAction : public ToolAction {
David Blaikie39808ff2014-04-25 14:49:37 +0000464 std::vector<std::unique_ptr<ASTUnit>> &ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000465
466public:
David Blaikie39808ff2014-04-25 14:49:37 +0000467 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000468
Manuel Klimek64083012013-11-07 23:18:05 +0000469 bool runInvocation(CompilerInvocation *Invocation, FileManager *Files,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000470 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000471 DiagnosticConsumer *DiagConsumer) override {
David Blaikie103a2de2014-04-25 17:01:33 +0000472 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000473 Invocation, std::move(PCHContainerOps),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000474 CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
475 DiagConsumer,
Benjamin Kramerbc632902015-10-06 14:45:20 +0000476 /*ShouldOwnClient=*/false),
477 Files);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000478 if (!AST)
479 return false;
480
David Blaikie39808ff2014-04-25 14:49:37 +0000481 ASTs.push_back(std::move(AST));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000482 return true;
483 }
484};
485
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000486}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000487
David Blaikie39808ff2014-04-25 14:49:37 +0000488int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000489 ASTBuilderAction Action(ASTs);
490 return run(&Action);
491}
492
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000493std::unique_ptr<ASTUnit>
494buildASTFromCode(const Twine &Code, const Twine &FileName,
495 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
496 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000497 "clang-tool", std::move(PCHContainerOps));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000498}
499
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000500std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
501 const Twine &Code, const std::vector<std::string> &Args,
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000502 const Twine &FileName, const Twine &ToolName,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000503 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000504 SmallString<16> FileNameStorage;
505 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
506
David Blaikie39808ff2014-04-25 14:49:37 +0000507 std::vector<std::unique_ptr<ASTUnit>> ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000508 ASTBuilderAction Action(ASTs);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000509 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
510 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
511 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
512 new vfs::InMemoryFileSystem);
513 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Benjamin Kramerfa3dcf22015-10-06 15:04:13 +0000514 llvm::IntrusiveRefCntPtr<FileManager> Files(
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000515 new FileManager(FileSystemOptions(), OverlayFileSystem));
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000516 ToolInvocation Invocation(getSyntaxOnlyToolArgs(ToolName, Args, FileNameRef),
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000517 &Action, Files.get(), std::move(PCHContainerOps));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000518
519 SmallString<1024> CodeStorage;
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000520 InMemoryFileSystem->addFile(FileNameRef, 0,
521 llvm::MemoryBuffer::getMemBuffer(
522 Code.toNullTerminatedStringRef(CodeStorage)));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000523 if (!Invocation.run())
Craig Topperccbc35e2014-05-20 04:51:16 +0000524 return nullptr;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000525
526 assert(ASTs.size() == 1);
David Blaikie103a2de2014-04-25 17:01:33 +0000527 return std::move(ASTs[0]);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000528}
529
Manuel Klimek47c245a2012-04-04 12:07:46 +0000530} // end namespace tooling
531} // end namespace clang