blob: 06440660615a48a4b981946d12b1c9c66ca7ffbc [file] [log] [blame]
Eugene Zelenko6366efe2018-03-14 21:05:51 +00001//===- Tooling.cpp - Running clang standalone tools -----------------------===//
Manuel Klimek47c245a2012-04-04 12:07:46 +00002//
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"
Eugene Zelenko6366efe2018-03-14 21:05:51 +000016#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/DiagnosticIDs.h"
18#include "clang/Basic/DiagnosticOptions.h"
19#include "clang/Basic/FileManager.h"
20#include "clang/Basic/FileSystemOptions.h"
21#include "clang/Basic/LLVM.h"
22#include "clang/Basic/VirtualFileSystem.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000023#include "clang/Driver/Compilation.h"
24#include "clang/Driver/Driver.h"
Eugene Zelenko6366efe2018-03-14 21:05:51 +000025#include "clang/Driver/Job.h"
Olivier Goffartb37a5e32016-08-30 17:42:29 +000026#include "clang/Driver/Options.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000027#include "clang/Driver/Tool.h"
Manuel Klimek9b30e2b2015-10-06 10:45:03 +000028#include "clang/Driver/ToolChain.h"
Peter Collingbournec689ee72013-11-06 20:12:45 +000029#include "clang/Frontend/ASTUnit.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000030#include "clang/Frontend/CompilerInstance.h"
Eugene Zelenko6366efe2018-03-14 21:05:51 +000031#include "clang/Frontend/CompilerInvocation.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000032#include "clang/Frontend/FrontendDiagnostic.h"
Eugene Zelenko6366efe2018-03-14 21:05:51 +000033#include "clang/Frontend/FrontendOptions.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000034#include "clang/Frontend/TextDiagnosticPrinter.h"
Eugene Zelenko6366efe2018-03-14 21:05:51 +000035#include "clang/Lex/HeaderSearchOptions.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000036#include "clang/Lex/PreprocessorOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Tooling/ArgumentsAdjusters.h"
38#include "clang/Tooling/CompilationDatabase.h"
Eugene Zelenko6366efe2018-03-14 21:05:51 +000039#include "llvm/ADT/ArrayRef.h"
40#include "llvm/ADT/IntrusiveRefCntPtr.h"
41#include "llvm/ADT/SmallString.h"
42#include "llvm/ADT/StringRef.h"
43#include "llvm/ADT/Twine.h"
Alp Toker1d257e12014-06-04 03:28:55 +000044#include "llvm/Config/llvm-config.h"
Olivier Goffartb37a5e32016-08-30 17:42:29 +000045#include "llvm/Option/ArgList.h"
Eugene Zelenko6366efe2018-03-14 21:05:51 +000046#include "llvm/Option/OptTable.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000047#include "llvm/Option/Option.h"
Eugene Zelenko6366efe2018-03-14 21:05:51 +000048#include "llvm/Support/Casting.h"
Edwin Vane34794c52013-03-15 20:14:01 +000049#include "llvm/Support/Debug.h"
Eugene Zelenko6366efe2018-03-14 21:05:51 +000050#include "llvm/Support/ErrorHandling.h"
NAKAMURA Takumif0c87792012-04-04 13:59:36 +000051#include "llvm/Support/FileSystem.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000052#include "llvm/Support/Host.h"
Eugene Zelenko6366efe2018-03-14 21:05:51 +000053#include "llvm/Support/MemoryBuffer.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000054#include "llvm/Support/Path.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000055#include "llvm/Support/raw_ostream.h"
Eugene Zelenko6366efe2018-03-14 21:05:51 +000056#include <cassert>
57#include <cstring>
58#include <memory>
59#include <string>
60#include <system_error>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000061#include <utility>
Eugene Zelenko6366efe2018-03-14 21:05:51 +000062#include <vector>
Manuel Klimek47c245a2012-04-04 12:07:46 +000063
Chandler Carruth57f5fbe2014-04-21 22:55:36 +000064#define DEBUG_TYPE "clang-tooling"
65
Eugene Zelenko6366efe2018-03-14 21:05:51 +000066using namespace clang;
67using namespace tooling;
Manuel Klimek47c245a2012-04-04 12:07:46 +000068
Eugene Zelenko6366efe2018-03-14 21:05:51 +000069ToolAction::~ToolAction() = default;
Peter Collingbournec689ee72013-11-06 20:12:45 +000070
Eugene Zelenko6366efe2018-03-14 21:05:51 +000071FrontendActionFactory::~FrontendActionFactory() = default;
Manuel Klimek47c245a2012-04-04 12:07:46 +000072
73// FIXME: This file contains structural duplication with other parts of the
74// code that sets up a compiler to run tools on it, and we should refactor
75// it to be based on the same framework.
76
77/// \brief Builds a clang driver initialized for running clang tools.
Eugene Zelenko6366efe2018-03-14 21:05:51 +000078static driver::Driver *newDriver(
79 DiagnosticsEngine *Diagnostics, const char *BinaryName,
Benjamin Kramer407eb792015-10-09 13:03:25 +000080 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Eugene Zelenko6366efe2018-03-14 21:05:51 +000081 driver::Driver *CompilerDriver =
82 new driver::Driver(BinaryName, llvm::sys::getDefaultTargetTriple(),
83 *Diagnostics, std::move(VFS));
Manuel Klimek47c245a2012-04-04 12:07:46 +000084 CompilerDriver->setTitle("clang_based_tool");
85 return CompilerDriver;
86}
87
88/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
89///
Eugene Zelenko6366efe2018-03-14 21:05:51 +000090/// Returns nullptr on error.
Reid Kleckner898229a2013-06-14 17:17:23 +000091static const llvm::opt::ArgStringList *getCC1Arguments(
Eugene Zelenko6366efe2018-03-14 21:05:51 +000092 DiagnosticsEngine *Diagnostics, driver::Compilation *Compilation) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000093 // We expect to get back exactly one Command job, if we didn't something
94 // failed. Extract that job from the Compilation.
Eugene Zelenko6366efe2018-03-14 21:05:51 +000095 const driver::JobList &Jobs = Compilation->getJobs();
96 if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000097 SmallString<256> error_msg;
Manuel Klimek47c245a2012-04-04 12:07:46 +000098 llvm::raw_svector_ostream error_stream(error_msg);
Hans Wennborgb212b342013-09-12 18:23:34 +000099 Jobs.Print(error_stream, "; ", true);
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000100 Diagnostics->Report(diag::err_fe_expected_compiler_job)
Manuel Klimek47c245a2012-04-04 12:07:46 +0000101 << error_stream.str();
Craig Topperccbc35e2014-05-20 04:51:16 +0000102 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000103 }
104
105 // The one job we find should be to invoke clang again.
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000106 const auto &Cmd = cast<driver::Command>(*Jobs.begin());
David Blaikiec11bf802014-09-04 16:04:28 +0000107 if (StringRef(Cmd.getCreator().getName()) != "clang") {
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000108 Diagnostics->Report(diag::err_fe_expected_clang_command);
Craig Topperccbc35e2014-05-20 04:51:16 +0000109 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000110 }
111
David Blaikiec11bf802014-09-04 16:04:28 +0000112 return &Cmd.getArguments();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000113}
114
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000115namespace clang {
116namespace tooling {
117
Manuel Klimek47c245a2012-04-04 12:07:46 +0000118/// \brief Returns a clang build invocation initialized from the CC1 flags.
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000119CompilerInvocation *newInvocation(
120 DiagnosticsEngine *Diagnostics, const llvm::opt::ArgStringList &CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000121 assert(!CC1Args.empty() && "Must at least contain the program name!");
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000122 CompilerInvocation *Invocation = new CompilerInvocation;
123 CompilerInvocation::CreateFromArgs(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000124 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
125 *Diagnostics);
126 Invocation->getFrontendOpts().DisableFree = false;
Nick Lewycky39dc9f82013-06-25 17:01:21 +0000127 Invocation->getCodeGenOpts().DisableFree = false;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000128 return Invocation;
129}
130
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000131bool runToolOnCode(FrontendAction *ToolAction, const Twine &Code,
Roman Lebedev497fd982018-02-27 15:54:55 +0000132 const Twine &FileName,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000133 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
Roman Lebedev497fd982018-02-27 15:54:55 +0000134 return runToolOnCodeWithArgs(ToolAction, Code, std::vector<std::string>(),
135 FileName, "clang-tool",
136 std::move(PCHContainerOps));
Nico Weber077a53e2012-08-30 02:02:19 +0000137}
138
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000139} // namespace tooling
140} // namespace clang
141
Peter Collingbournec689ee72013-11-06 20:12:45 +0000142static std::vector<std::string>
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000143getSyntaxOnlyToolArgs(const Twine &ToolName,
144 const std::vector<std::string> &ExtraArgs,
Peter Collingbournec689ee72013-11-06 20:12:45 +0000145 StringRef FileName) {
146 std::vector<std::string> Args;
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000147 Args.push_back(ToolName.str());
Peter Collingbournec689ee72013-11-06 20:12:45 +0000148 Args.push_back("-fsyntax-only");
149 Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
150 Args.push_back(FileName.str());
151 return Args;
152}
153
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000154namespace clang {
155namespace tooling {
156
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000157bool runToolOnCodeWithArgs(
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000158 FrontendAction *ToolAction, const Twine &Code,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000159 const std::vector<std::string> &Args, const Twine &FileName,
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000160 const Twine &ToolName,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000161 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
162 const FileContentMappings &VirtualMappedFiles) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000163 SmallString<16> FileNameStorage;
164 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000165 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
166 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
167 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
168 new vfs::InMemoryFileSystem);
169 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000170 llvm::IntrusiveRefCntPtr<FileManager> Files(
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000171 new FileManager(FileSystemOptions(), OverlayFileSystem));
Sterling Augustine6b030ab2017-07-06 22:47:19 +0000172 ArgumentsAdjuster Adjuster = getClangStripDependencyFileAdjuster();
173 ToolInvocation Invocation(
174 getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef),
Roman Lebedev497fd982018-02-27 15:54:55 +0000175 ToolAction, Files.get(),
176 std::move(PCHContainerOps));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000177
178 SmallString<1024> CodeStorage;
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000179 InMemoryFileSystem->addFile(FileNameRef, 0,
180 llvm::MemoryBuffer::getMemBuffer(
181 Code.toNullTerminatedStringRef(CodeStorage)));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000182
183 for (auto &FilenameWithContent : VirtualMappedFiles) {
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000184 InMemoryFileSystem->addFile(
185 FilenameWithContent.first, 0,
186 llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000187 }
188
Manuel Klimek47c245a2012-04-04 12:07:46 +0000189 return Invocation.run();
190}
191
Manuel Klimek65fd0e12012-07-10 13:10:51 +0000192std::string getAbsolutePath(StringRef File) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000193 StringRef RelativePath(File);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000194 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimek47c245a2012-04-04 12:07:46 +0000195 if (RelativePath.startswith("./")) {
196 RelativePath = RelativePath.substr(strlen("./"));
197 }
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000198
199 SmallString<1024> AbsolutePath = RelativePath;
Rafael Espindolac0809172014-06-12 14:02:15 +0000200 std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000201 assert(!EC);
Rafael Espindola0b8e4a12013-08-10 04:25:53 +0000202 (void)EC;
Benjamin Kramer2d4d8cb2013-09-11 11:23:15 +0000203 llvm::sys::path::native(AbsolutePath);
204 return AbsolutePath.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000205}
206
Manuel Klimek9b30e2b2015-10-06 10:45:03 +0000207void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
208 StringRef InvokedAs) {
209 if (!CommandLine.empty() && !InvokedAs.empty()) {
210 bool AlreadyHasTarget = false;
211 bool AlreadyHasMode = false;
212 // Skip CommandLine[0].
213 for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();
214 ++Token) {
215 StringRef TokenRef(*Token);
216 AlreadyHasTarget |=
217 (TokenRef == "-target" || TokenRef.startswith("-target="));
218 AlreadyHasMode |= (TokenRef == "--driver-mode" ||
219 TokenRef.startswith("--driver-mode="));
220 }
221 auto TargetMode =
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000222 driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs);
Serge Pavlov4e769842017-08-29 05:22:26 +0000223 if (!AlreadyHasMode && TargetMode.DriverMode) {
224 CommandLine.insert(++CommandLine.begin(), TargetMode.DriverMode);
Manuel Klimek9b30e2b2015-10-06 10:45:03 +0000225 }
Serge Pavlov4e769842017-08-29 05:22:26 +0000226 if (!AlreadyHasTarget && TargetMode.TargetIsValid) {
227 CommandLine.insert(++CommandLine.begin(), {"-target",
228 TargetMode.TargetPrefix});
Manuel Klimek9b30e2b2015-10-06 10:45:03 +0000229 }
230 }
231}
232
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000233} // namespace tooling
234} // namespace clang
235
Peter Collingbournec689ee72013-11-06 20:12:45 +0000236namespace {
237
238class SingleFrontendActionFactory : public FrontendActionFactory {
Roman Lebedev497fd982018-02-27 15:54:55 +0000239 FrontendAction *Action;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000240
241public:
Roman Lebedev497fd982018-02-27 15:54:55 +0000242 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000243
Roman Lebedev497fd982018-02-27 15:54:55 +0000244 FrontendAction *create() override { return Action; }
Peter Collingbournec689ee72013-11-06 20:12:45 +0000245};
246
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000247} // namespace
Peter Collingbournec689ee72013-11-06 20:12:45 +0000248
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000249ToolInvocation::ToolInvocation(
250 std::vector<std::string> CommandLine, ToolAction *Action,
251 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
252 : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false),
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000253 Files(Files), PCHContainerOps(std::move(PCHContainerOps)) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000254
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000255ToolInvocation::ToolInvocation(
Roman Lebedev497fd982018-02-27 15:54:55 +0000256 std::vector<std::string> CommandLine, FrontendAction *FAction,
257 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000258 : CommandLine(std::move(CommandLine)),
Roman Lebedev497fd982018-02-27 15:54:55 +0000259 Action(new SingleFrontendActionFactory(FAction)), OwnsAction(true),
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000260 Files(Files), PCHContainerOps(std::move(PCHContainerOps)) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000261
262ToolInvocation::~ToolInvocation() {
263 if (OwnsAction)
264 delete Action;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000265}
266
267void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi4de31652012-06-02 15:34:21 +0000268 SmallString<1024> PathStorage;
269 llvm::sys::path::native(FilePath, PathStorage);
270 MappedFileContents[PathStorage] = Content;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000271}
272
273bool ToolInvocation::run() {
274 std::vector<const char*> Argv;
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000275 for (const std::string &Str : CommandLine)
276 Argv.push_back(Str.c_str());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000277 const char *const BinaryName = Argv[0];
Douglas Gregor811db4e2012-10-23 22:26:28 +0000278 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Olivier Goffartb37a5e32016-08-30 17:42:29 +0000279 unsigned MissingArgIndex, MissingArgCount;
David Blaikie0aaa7622017-01-13 17:34:15 +0000280 std::unique_ptr<llvm::opt::OptTable> Opts = driver::createDriverOptTable();
Richard Trieu070937a2016-08-30 21:12:48 +0000281 llvm::opt::InputArgList ParsedArgs = Opts->ParseArgs(
282 ArrayRef<const char *>(Argv).slice(1), MissingArgIndex, MissingArgCount);
Olivier Goffartb37a5e32016-08-30 17:42:29 +0000283 ParseDiagnosticArgs(*DiagOpts, ParsedArgs);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000284 TextDiagnosticPrinter DiagnosticPrinter(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000285 llvm::errs(), &*DiagOpts);
286 DiagnosticsEngine Diagnostics(
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000287 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Manuel Klimek64083012013-11-07 23:18:05 +0000288 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000289
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000290 const std::unique_ptr<driver::Driver> Driver(
Benjamin Kramer407eb792015-10-09 13:03:25 +0000291 newDriver(&Diagnostics, BinaryName, Files->getVirtualFileSystem()));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000292 // Since the input might only be virtual, don't check whether it exists.
293 Driver->setCheckInputsExist(false);
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000294 const std::unique_ptr<driver::Compilation> Compilation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000295 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
Serge Pavlovc46064c2017-05-24 11:57:37 +0000296 if (!Compilation)
297 return false;
Reid Kleckner898229a2013-06-14 17:17:23 +0000298 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000299 &Diagnostics, Compilation.get());
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000300 if (!CC1Args)
Manuel Klimek47c245a2012-04-04 12:07:46 +0000301 return false;
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000302 std::unique_ptr<CompilerInvocation> Invocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000303 newInvocation(&Diagnostics, *CC1Args));
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000304 // FIXME: remove this when all users have migrated!
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000305 for (const auto &It : MappedFileContents) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000306 // Inject the code as the given file name into the preprocessor options.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000307 std::unique_ptr<llvm::MemoryBuffer> Input =
308 llvm::MemoryBuffer::getMemBuffer(It.getValue());
309 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
310 Input.release());
Peter Collingbournec689ee72013-11-06 20:12:45 +0000311 }
David Blaikieea4395e2017-01-06 19:49:01 +0000312 return runInvocation(BinaryName, Compilation.get(), std::move(Invocation),
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000313 std::move(PCHContainerOps));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000314}
315
Manuel Klimek47c245a2012-04-04 12:07:46 +0000316bool ToolInvocation::runInvocation(
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000317 const char *BinaryName, driver::Compilation *Compilation,
318 std::shared_ptr<CompilerInvocation> Invocation,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000319 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000320 // Show the invocation, with -v.
321 if (Invocation->getHeaderSearchOpts().Verbose) {
322 llvm::errs() << "clang Invocation:\n";
Hans Wennborgb212b342013-09-12 18:23:34 +0000323 Compilation->getJobs().Print(llvm::errs(), "\n", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000324 llvm::errs() << "\n";
325 }
326
David Blaikieea4395e2017-01-06 19:49:01 +0000327 return Action->runInvocation(std::move(Invocation), Files,
328 std::move(PCHContainerOps), DiagConsumer);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000329}
330
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000331bool FrontendActionFactory::runInvocation(
David Blaikieea4395e2017-01-06 19:49:01 +0000332 std::shared_ptr<CompilerInvocation> Invocation, FileManager *Files,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000333 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
334 DiagnosticConsumer *DiagConsumer) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000335 // Create a compiler instance to handle the actual work.
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000336 CompilerInstance Compiler(std::move(PCHContainerOps));
David Blaikieea4395e2017-01-06 19:49:01 +0000337 Compiler.setInvocation(std::move(Invocation));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000338 Compiler.setFileManager(Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000339
Peter Collingbournec689ee72013-11-06 20:12:45 +0000340 // The FrontendAction can have lifetime requirements for Compiler or its
341 // members, and we need to ensure it's deleted earlier than Compiler. So we
Ahmed Charlesb8984322014-03-07 20:03:18 +0000342 // pass it to an std::unique_ptr declared after the Compiler variable.
343 std::unique_ptr<FrontendAction> ScopedToolAction(create());
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000344
Alp Toker77273fc2014-05-16 13:45:29 +0000345 // Create the compiler's actual diagnostics engine.
Manuel Klimek64083012013-11-07 23:18:05 +0000346 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000347 if (!Compiler.hasDiagnostics())
348 return false;
349
350 Compiler.createSourceManager(*Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000351
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000352 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000353
Manuel Klimek3aad8552012-07-31 13:56:54 +0000354 Files->clearStatCaches();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000355 return Success;
356}
357
Manuel Klimek47c245a2012-04-04 12:07:46 +0000358ClangTool::ClangTool(const CompilationDatabase &Compilations,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000359 ArrayRef<std::string> SourcePaths,
Ilya Biryukov5da21ed2018-01-23 12:30:02 +0000360 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
361 IntrusiveRefCntPtr<vfs::FileSystem> BaseFS)
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000362 : Compilations(Compilations), SourcePaths(SourcePaths),
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000363 PCHContainerOps(std::move(PCHContainerOps)),
Alexander Kornienko156adaf2018-03-27 14:02:06 +0000364 OverlayFileSystem(new vfs::OverlayFileSystem(std::move(BaseFS))),
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000365 InMemoryFileSystem(new vfs::InMemoryFileSystem),
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000366 Files(new FileManager(FileSystemOptions(), OverlayFileSystem)) {
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000367 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000368 appendArgumentsAdjuster(getClangStripOutputAdjuster());
369 appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
Sterling Augustine78f46122017-07-14 18:33:30 +0000370 appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000371}
372
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000373ClangTool::~ClangTool() = default;
Manuel Klimek64083012013-11-07 23:18:05 +0000374
Manuel Klimek47c245a2012-04-04 12:07:46 +0000375void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
376 MappedFileContents.push_back(std::make_pair(FilePath, Content));
377}
378
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000379void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
Eric Liu826b7832017-10-26 10:38:14 +0000380 ArgsAdjuster = combineAdjusters(std::move(ArgsAdjuster), std::move(Adjuster));
Manuel Klimekd91ac932013-06-04 14:44:44 +0000381}
382
383void ClangTool::clearArgumentsAdjusters() {
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000384 ArgsAdjuster = nullptr;
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000385}
386
Benjamin Kramerb5737c12016-04-21 10:18:18 +0000387static void injectResourceDir(CommandLineArguments &Args, const char *Argv0,
388 void *MainAddr) {
389 // Allow users to override the resource dir.
390 for (StringRef Arg : Args)
391 if (Arg.startswith("-resource-dir"))
392 return;
393
394 // If there's no override in place add our resource dir.
395 Args.push_back("-resource-dir=" +
396 CompilerInvocation::GetResourcesPath(Argv0, MainAddr));
397}
398
Peter Collingbournec689ee72013-11-06 20:12:45 +0000399int ClangTool::run(ToolAction *Action) {
Alexander Kornienko8388d242012-06-04 19:02:59 +0000400 // Exists solely for the purpose of lookup of the resource path.
401 // This just needs to be some symbol in the binary.
402 static int StaticSymbol;
Alexander Kornienko8388d242012-06-04 19:02:59 +0000403
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000404 llvm::SmallString<128> InitialDirectory;
405 if (std::error_code EC = llvm::sys::fs::current_path(InitialDirectory))
406 llvm::report_fatal_error("Cannot detect current path: " +
407 Twine(EC.message()));
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000408
409 // First insert all absolute paths into the in-memory VFS. These are global
410 // for all compile commands.
411 if (SeenWorkingDirectories.insert("/").second)
412 for (const auto &MappedFile : MappedFileContents)
413 if (llvm::sys::path::is_absolute(MappedFile.first))
414 InMemoryFileSystem->addFile(
415 MappedFile.first, 0,
416 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
417
Manuel Klimek47c245a2012-04-04 12:07:46 +0000418 bool ProcessingFailed = false;
Eric Liu3a2cf862018-02-02 18:19:22 +0000419 bool FileSkipped = false;
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000420 for (const auto &SourcePath : SourcePaths) {
421 std::string File(getAbsolutePath(SourcePath));
422
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000423 // Currently implementations of CompilationDatabase::getCompileCommands can
424 // change the state of the file system (e.g. prepare generated headers), so
425 // this method needs to run right before we invoke the tool, as the next
426 // file may require a different (incompatible) state of the file system.
427 //
428 // FIXME: Make the compilation database interface more explicit about the
429 // requirements to the order of invocation of its members.
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000430 std::vector<CompileCommand> CompileCommandsForFile =
431 Compilations.getCompileCommands(File);
432 if (CompileCommandsForFile.empty()) {
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000433 llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
Eric Liu3a2cf862018-02-02 18:19:22 +0000434 FileSkipped = true;
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000435 continue;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000436 }
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000437 for (CompileCommand &CompileCommand : CompileCommandsForFile) {
438 // FIXME: chdir is thread hostile; on the other hand, creating the same
439 // behavior as chdir is complex: chdir resolves the path once, thus
440 // guaranteeing that all subsequent relative path operations work
441 // on the same path the original chdir resulted in. This makes a
442 // difference for example on network filesystems, where symlinks might be
443 // switched during runtime of the tool. Fixing this depends on having a
444 // file system abstraction that allows openat() style interactions.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000445 if (OverlayFileSystem->setCurrentWorkingDirectory(
446 CompileCommand.Directory))
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000447 llvm::report_fatal_error("Cannot chdir into \"" +
448 Twine(CompileCommand.Directory) + "\n!");
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000449
450 // Now fill the in-memory VFS with the relative file mappings so it will
451 // have the correct relative paths. We never remove mappings but that
452 // should be fine.
453 if (SeenWorkingDirectories.insert(CompileCommand.Directory).second)
454 for (const auto &MappedFile : MappedFileContents)
455 if (!llvm::sys::path::is_absolute(MappedFile.first))
456 InMemoryFileSystem->addFile(
457 MappedFile.first, 0,
458 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
459
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000460 std::vector<std::string> CommandLine = CompileCommand.CommandLine;
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000461 if (ArgsAdjuster)
Alexander Kornienko857b10f2015-11-05 02:19:53 +0000462 CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000463 assert(!CommandLine.empty());
Benjamin Kramerb5737c12016-04-21 10:18:18 +0000464
465 // Add the resource dir based on the binary of this tool. argv[0] in the
466 // compilation database may refer to a different compiler and we want to
467 // pick up the very same standard library that compiler is using. The
468 // builtin headers in the resource dir need to match the exact clang
469 // version the tool is using.
470 // FIXME: On linux, GetMainExecutable is independent of the value of the
471 // first argument, thus allowing ClangTool and runToolOnCode to just
472 // pass in made-up names here. Make sure this works on other platforms.
473 injectResourceDir(CommandLine, "clang_tool", &StaticSymbol);
474
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000475 // FIXME: We need a callback mechanism for the tool writer to output a
476 // customized message for each file.
477 DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000478 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
479 PCHContainerOps);
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000480 Invocation.setDiagnosticConsumer(DiagConsumer);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000481
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000482 if (!Invocation.run()) {
483 // FIXME: Diagnostics should be used instead.
484 llvm::errs() << "Error while processing " << File << ".\n";
485 ProcessingFailed = true;
486 }
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000487 // Return to the initial directory to correctly resolve next file by
488 // relative path.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000489 if (OverlayFileSystem->setCurrentWorkingDirectory(InitialDirectory.c_str()))
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000490 llvm::report_fatal_error("Cannot chdir into \"" +
491 Twine(InitialDirectory) + "\n!");
Manuel Klimek47c245a2012-04-04 12:07:46 +0000492 }
493 }
Eric Liu3a2cf862018-02-02 18:19:22 +0000494 return ProcessingFailed ? 1 : (FileSkipped ? 2 : 0);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000495}
496
Peter Collingbournec689ee72013-11-06 20:12:45 +0000497namespace {
498
499class ASTBuilderAction : public ToolAction {
David Blaikie39808ff2014-04-25 14:49:37 +0000500 std::vector<std::unique_ptr<ASTUnit>> &ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000501
502public:
David Blaikie39808ff2014-04-25 14:49:37 +0000503 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000504
David Blaikieea4395e2017-01-06 19:49:01 +0000505 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
506 FileManager *Files,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000507 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000508 DiagnosticConsumer *DiagConsumer) override {
David Blaikie103a2de2014-04-25 17:01:33 +0000509 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000510 Invocation, std::move(PCHContainerOps),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000511 CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
512 DiagConsumer,
Benjamin Kramerbc632902015-10-06 14:45:20 +0000513 /*ShouldOwnClient=*/false),
514 Files);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000515 if (!AST)
516 return false;
517
David Blaikie39808ff2014-04-25 14:49:37 +0000518 ASTs.push_back(std::move(AST));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000519 return true;
520 }
521};
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000522
523} // namespace
Peter Collingbournec689ee72013-11-06 20:12:45 +0000524
David Blaikie39808ff2014-04-25 14:49:37 +0000525int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000526 ASTBuilderAction Action(ASTs);
527 return run(&Action);
528}
529
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000530namespace clang {
531namespace tooling {
532
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000533std::unique_ptr<ASTUnit>
534buildASTFromCode(const Twine &Code, const Twine &FileName,
535 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
536 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000537 "clang-tool", std::move(PCHContainerOps));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000538}
539
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000540std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
541 const Twine &Code, const std::vector<std::string> &Args,
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000542 const Twine &FileName, const Twine &ToolName,
Sterling Augustine1cda1d72017-07-06 21:02:52 +0000543 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
544 ArgumentsAdjuster Adjuster) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000545 SmallString<16> FileNameStorage;
546 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
547
David Blaikie39808ff2014-04-25 14:49:37 +0000548 std::vector<std::unique_ptr<ASTUnit>> ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000549 ASTBuilderAction Action(ASTs);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000550 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
551 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
552 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
553 new vfs::InMemoryFileSystem);
554 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Benjamin Kramerfa3dcf22015-10-06 15:04:13 +0000555 llvm::IntrusiveRefCntPtr<FileManager> Files(
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000556 new FileManager(FileSystemOptions(), OverlayFileSystem));
Sterling Augustine1cda1d72017-07-06 21:02:52 +0000557
558 ToolInvocation Invocation(
559 getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef),
560 &Action, Files.get(), std::move(PCHContainerOps));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000561
562 SmallString<1024> CodeStorage;
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000563 InMemoryFileSystem->addFile(FileNameRef, 0,
564 llvm::MemoryBuffer::getMemBuffer(
565 Code.toNullTerminatedStringRef(CodeStorage)));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000566 if (!Invocation.run())
Craig Topperccbc35e2014-05-20 04:51:16 +0000567 return nullptr;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000568
569 assert(ASTs.size() == 1);
David Blaikie103a2de2014-04-25 17:01:33 +0000570 return std::move(ASTs[0]);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000571}
572
Eugene Zelenko6366efe2018-03-14 21:05:51 +0000573} // namespace tooling
574} // namespace clang