blob: 662f02dca2a662b8480eaac59adae49cb9d9c7dd [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"
Manuel Klimek47c245a2012-04-04 12:07:46 +000016#include "clang/Driver/Compilation.h"
17#include "clang/Driver/Driver.h"
Olivier Goffartb37a5e32016-08-30 17:42:29 +000018#include "clang/Driver/Options.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000019#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"
Mehdi Amini9670f842016-07-18 19:02:11 +000025#include "clang/Lex/PreprocessorOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Tooling/ArgumentsAdjusters.h"
27#include "clang/Tooling/CompilationDatabase.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000028#include "llvm/ADT/STLExtras.h"
Alp Toker1d257e12014-06-04 03:28:55 +000029#include "llvm/Config/llvm-config.h"
Olivier Goffartb37a5e32016-08-30 17:42:29 +000030#include "llvm/Option/ArgList.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000031#include "llvm/Option/Option.h"
Edwin Vane34794c52013-03-15 20:14:01 +000032#include "llvm/Support/Debug.h"
NAKAMURA Takumif0c87792012-04-04 13:59:36 +000033#include "llvm/Support/FileSystem.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000034#include "llvm/Support/Host.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000035#include "llvm/Support/Path.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000036#include "llvm/Support/raw_ostream.h"
Benjamin Kramercfeacf52016-05-27 14:27:13 +000037#include <utility>
Manuel Klimek47c245a2012-04-04 12:07:46 +000038
Chandler Carruth57f5fbe2014-04-21 22:55:36 +000039#define DEBUG_TYPE "clang-tooling"
40
Manuel Klimek47c245a2012-04-04 12:07:46 +000041namespace clang {
42namespace tooling {
43
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000044ToolAction::~ToolAction() {}
Peter Collingbournec689ee72013-11-06 20:12:45 +000045
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000046FrontendActionFactory::~FrontendActionFactory() {}
Manuel Klimek47c245a2012-04-04 12:07:46 +000047
48// FIXME: This file contains structural duplication with other parts of the
49// code that sets up a compiler to run tools on it, and we should refactor
50// it to be based on the same framework.
51
52/// \brief Builds a clang driver initialized for running clang tools.
Benjamin Kramer407eb792015-10-09 13:03:25 +000053static clang::driver::Driver *newDriver(
54 clang::DiagnosticsEngine *Diagnostics, const char *BinaryName,
55 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Benjamin Kramer7320b992016-06-15 14:20:56 +000056 clang::driver::Driver *CompilerDriver =
57 new clang::driver::Driver(BinaryName, llvm::sys::getDefaultTargetTriple(),
58 *Diagnostics, std::move(VFS));
Manuel Klimek47c245a2012-04-04 12:07:46 +000059 CompilerDriver->setTitle("clang_based_tool");
60 return CompilerDriver;
61}
62
63/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
64///
65/// Returns NULL on error.
Reid Kleckner898229a2013-06-14 17:17:23 +000066static const llvm::opt::ArgStringList *getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +000067 clang::DiagnosticsEngine *Diagnostics,
68 clang::driver::Compilation *Compilation) {
69 // We expect to get back exactly one Command job, if we didn't something
70 // failed. Extract that job from the Compilation.
71 const clang::driver::JobList &Jobs = Compilation->getJobs();
Justin Bogneraab97922014-10-03 01:04:53 +000072 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000073 SmallString<256> error_msg;
Manuel Klimek47c245a2012-04-04 12:07:46 +000074 llvm::raw_svector_ostream error_stream(error_msg);
Hans Wennborgb212b342013-09-12 18:23:34 +000075 Jobs.Print(error_stream, "; ", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +000076 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
77 << error_stream.str();
Craig Topperccbc35e2014-05-20 04:51:16 +000078 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +000079 }
80
81 // The one job we find should be to invoke clang again.
David Blaikiec11bf802014-09-04 16:04:28 +000082 const clang::driver::Command &Cmd =
Justin Bogneraab97922014-10-03 01:04:53 +000083 cast<clang::driver::Command>(*Jobs.begin());
David Blaikiec11bf802014-09-04 16:04:28 +000084 if (StringRef(Cmd.getCreator().getName()) != "clang") {
Manuel Klimek47c245a2012-04-04 12:07:46 +000085 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
Craig Topperccbc35e2014-05-20 04:51:16 +000086 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +000087 }
88
David Blaikiec11bf802014-09-04 16:04:28 +000089 return &Cmd.getArguments();
Manuel Klimek47c245a2012-04-04 12:07:46 +000090}
91
92/// \brief Returns a clang build invocation initialized from the CC1 flags.
Manuel Klimekbea7dfb2015-03-28 00:42:36 +000093clang::CompilerInvocation *newInvocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +000094 clang::DiagnosticsEngine *Diagnostics,
Reid Kleckner898229a2013-06-14 17:17:23 +000095 const llvm::opt::ArgStringList &CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000096 assert(!CC1Args.empty() && "Must at least contain the program name!");
97 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
98 clang::CompilerInvocation::CreateFromArgs(
99 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
100 *Diagnostics);
101 Invocation->getFrontendOpts().DisableFree = false;
Nick Lewycky39dc9f82013-06-25 17:01:21 +0000102 Invocation->getCodeGenOpts().DisableFree = false;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000103 return Invocation;
104}
105
106bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000107 const Twine &FileName,
108 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
109 return runToolOnCodeWithArgs(ToolAction, Code, std::vector<std::string>(),
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000110 FileName, "clang-tool",
111 std::move(PCHContainerOps));
Nico Weber077a53e2012-08-30 02:02:19 +0000112}
113
Peter Collingbournec689ee72013-11-06 20:12:45 +0000114static std::vector<std::string>
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000115getSyntaxOnlyToolArgs(const Twine &ToolName,
116 const std::vector<std::string> &ExtraArgs,
Peter Collingbournec689ee72013-11-06 20:12:45 +0000117 StringRef FileName) {
118 std::vector<std::string> Args;
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000119 Args.push_back(ToolName.str());
Peter Collingbournec689ee72013-11-06 20:12:45 +0000120 Args.push_back("-fsyntax-only");
121 Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
122 Args.push_back(FileName.str());
123 return Args;
124}
125
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000126bool runToolOnCodeWithArgs(
127 clang::FrontendAction *ToolAction, const Twine &Code,
128 const std::vector<std::string> &Args, const Twine &FileName,
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000129 const Twine &ToolName,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000130 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
131 const FileContentMappings &VirtualMappedFiles) {
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000132
Manuel Klimek47c245a2012-04-04 12:07:46 +0000133 SmallString<16> FileNameStorage;
134 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000135 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
136 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
137 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
138 new vfs::InMemoryFileSystem);
139 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000140 llvm::IntrusiveRefCntPtr<FileManager> Files(
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000141 new FileManager(FileSystemOptions(), OverlayFileSystem));
Sterling Augustine6b030ab2017-07-06 22:47:19 +0000142 ArgumentsAdjuster Adjuster = getClangStripDependencyFileAdjuster();
143 ToolInvocation Invocation(
144 getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef),
145 ToolAction, Files.get(),
146 std::move(PCHContainerOps));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000147
148 SmallString<1024> CodeStorage;
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000149 InMemoryFileSystem->addFile(FileNameRef, 0,
150 llvm::MemoryBuffer::getMemBuffer(
151 Code.toNullTerminatedStringRef(CodeStorage)));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000152
153 for (auto &FilenameWithContent : VirtualMappedFiles) {
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000154 InMemoryFileSystem->addFile(
155 FilenameWithContent.first, 0,
156 llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000157 }
158
Manuel Klimek47c245a2012-04-04 12:07:46 +0000159 return Invocation.run();
160}
161
Manuel Klimek65fd0e12012-07-10 13:10:51 +0000162std::string getAbsolutePath(StringRef File) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000163 StringRef RelativePath(File);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000164 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimek47c245a2012-04-04 12:07:46 +0000165 if (RelativePath.startswith("./")) {
166 RelativePath = RelativePath.substr(strlen("./"));
167 }
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000168
169 SmallString<1024> AbsolutePath = RelativePath;
Rafael Espindolac0809172014-06-12 14:02:15 +0000170 std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000171 assert(!EC);
Rafael Espindola0b8e4a12013-08-10 04:25:53 +0000172 (void)EC;
Benjamin Kramer2d4d8cb2013-09-11 11:23:15 +0000173 llvm::sys::path::native(AbsolutePath);
174 return AbsolutePath.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000175}
176
Manuel Klimek9b30e2b2015-10-06 10:45:03 +0000177void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
178 StringRef InvokedAs) {
179 if (!CommandLine.empty() && !InvokedAs.empty()) {
180 bool AlreadyHasTarget = false;
181 bool AlreadyHasMode = false;
182 // Skip CommandLine[0].
183 for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();
184 ++Token) {
185 StringRef TokenRef(*Token);
186 AlreadyHasTarget |=
187 (TokenRef == "-target" || TokenRef.startswith("-target="));
188 AlreadyHasMode |= (TokenRef == "--driver-mode" ||
189 TokenRef.startswith("--driver-mode="));
190 }
191 auto TargetMode =
192 clang::driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs);
193 if (!AlreadyHasMode && !TargetMode.second.empty()) {
194 CommandLine.insert(++CommandLine.begin(), TargetMode.second);
195 }
196 if (!AlreadyHasTarget && !TargetMode.first.empty()) {
197 CommandLine.insert(++CommandLine.begin(), {"-target", TargetMode.first});
198 }
199 }
200}
201
Peter Collingbournec689ee72013-11-06 20:12:45 +0000202namespace {
203
204class SingleFrontendActionFactory : public FrontendActionFactory {
205 FrontendAction *Action;
206
207public:
208 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
209
Craig Topperfb6b25b2014-03-15 04:29:04 +0000210 FrontendAction *create() override { return Action; }
Peter Collingbournec689ee72013-11-06 20:12:45 +0000211};
212
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000213}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000214
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000215ToolInvocation::ToolInvocation(
216 std::vector<std::string> CommandLine, ToolAction *Action,
217 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
218 : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false),
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000219 Files(Files), PCHContainerOps(std::move(PCHContainerOps)),
220 DiagConsumer(nullptr) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000221
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000222ToolInvocation::ToolInvocation(
223 std::vector<std::string> CommandLine, FrontendAction *FAction,
224 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000225 : CommandLine(std::move(CommandLine)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000226 Action(new SingleFrontendActionFactory(FAction)), OwnsAction(true),
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000227 Files(Files), PCHContainerOps(std::move(PCHContainerOps)),
228 DiagConsumer(nullptr) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000229
230ToolInvocation::~ToolInvocation() {
231 if (OwnsAction)
232 delete Action;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000233}
234
235void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi4de31652012-06-02 15:34:21 +0000236 SmallString<1024> PathStorage;
237 llvm::sys::path::native(FilePath, PathStorage);
238 MappedFileContents[PathStorage] = Content;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000239}
240
241bool ToolInvocation::run() {
242 std::vector<const char*> Argv;
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000243 for (const std::string &Str : CommandLine)
244 Argv.push_back(Str.c_str());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000245 const char *const BinaryName = Argv[0];
Douglas Gregor811db4e2012-10-23 22:26:28 +0000246 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Olivier Goffartb37a5e32016-08-30 17:42:29 +0000247 unsigned MissingArgIndex, MissingArgCount;
David Blaikie0aaa7622017-01-13 17:34:15 +0000248 std::unique_ptr<llvm::opt::OptTable> Opts = driver::createDriverOptTable();
Richard Trieu070937a2016-08-30 21:12:48 +0000249 llvm::opt::InputArgList ParsedArgs = Opts->ParseArgs(
250 ArrayRef<const char *>(Argv).slice(1), MissingArgIndex, MissingArgCount);
Olivier Goffartb37a5e32016-08-30 17:42:29 +0000251 ParseDiagnosticArgs(*DiagOpts, ParsedArgs);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000252 TextDiagnosticPrinter DiagnosticPrinter(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000253 llvm::errs(), &*DiagOpts);
254 DiagnosticsEngine Diagnostics(
Manuel Klimek64083012013-11-07 23:18:05 +0000255 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
256 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000257
Ahmed Charlesb8984322014-03-07 20:03:18 +0000258 const std::unique_ptr<clang::driver::Driver> Driver(
Benjamin Kramer407eb792015-10-09 13:03:25 +0000259 newDriver(&Diagnostics, BinaryName, Files->getVirtualFileSystem()));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000260 // Since the input might only be virtual, don't check whether it exists.
261 Driver->setCheckInputsExist(false);
Ahmed Charlesb8984322014-03-07 20:03:18 +0000262 const std::unique_ptr<clang::driver::Compilation> Compilation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000263 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
Serge Pavlovc46064c2017-05-24 11:57:37 +0000264 if (!Compilation)
265 return false;
Reid Kleckner898229a2013-06-14 17:17:23 +0000266 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000267 &Diagnostics, Compilation.get());
Craig Topperccbc35e2014-05-20 04:51:16 +0000268 if (!CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000269 return false;
270 }
Ahmed Charlesb8984322014-03-07 20:03:18 +0000271 std::unique_ptr<clang::CompilerInvocation> Invocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000272 newInvocation(&Diagnostics, *CC1Args));
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000273 // FIXME: remove this when all users have migrated!
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000274 for (const auto &It : MappedFileContents) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000275 // Inject the code as the given file name into the preprocessor options.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000276 std::unique_ptr<llvm::MemoryBuffer> Input =
277 llvm::MemoryBuffer::getMemBuffer(It.getValue());
278 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
279 Input.release());
Peter Collingbournec689ee72013-11-06 20:12:45 +0000280 }
David Blaikieea4395e2017-01-06 19:49:01 +0000281 return runInvocation(BinaryName, Compilation.get(), std::move(Invocation),
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000282 std::move(PCHContainerOps));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000283}
284
Manuel Klimek47c245a2012-04-04 12:07:46 +0000285bool ToolInvocation::runInvocation(
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000286 const char *BinaryName, clang::driver::Compilation *Compilation,
David Blaikieea4395e2017-01-06 19:49:01 +0000287 std::shared_ptr<clang::CompilerInvocation> Invocation,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000288 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000289 // Show the invocation, with -v.
290 if (Invocation->getHeaderSearchOpts().Verbose) {
291 llvm::errs() << "clang Invocation:\n";
Hans Wennborgb212b342013-09-12 18:23:34 +0000292 Compilation->getJobs().Print(llvm::errs(), "\n", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000293 llvm::errs() << "\n";
294 }
295
David Blaikieea4395e2017-01-06 19:49:01 +0000296 return Action->runInvocation(std::move(Invocation), Files,
297 std::move(PCHContainerOps), DiagConsumer);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000298}
299
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000300bool FrontendActionFactory::runInvocation(
David Blaikieea4395e2017-01-06 19:49:01 +0000301 std::shared_ptr<CompilerInvocation> Invocation, FileManager *Files,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000302 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
303 DiagnosticConsumer *DiagConsumer) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000304 // Create a compiler instance to handle the actual work.
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000305 clang::CompilerInstance Compiler(std::move(PCHContainerOps));
David Blaikieea4395e2017-01-06 19:49:01 +0000306 Compiler.setInvocation(std::move(Invocation));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000307 Compiler.setFileManager(Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000308
Peter Collingbournec689ee72013-11-06 20:12:45 +0000309 // The FrontendAction can have lifetime requirements for Compiler or its
310 // members, and we need to ensure it's deleted earlier than Compiler. So we
Ahmed Charlesb8984322014-03-07 20:03:18 +0000311 // pass it to an std::unique_ptr declared after the Compiler variable.
312 std::unique_ptr<FrontendAction> ScopedToolAction(create());
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000313
Alp Toker77273fc2014-05-16 13:45:29 +0000314 // Create the compiler's actual diagnostics engine.
Manuel Klimek64083012013-11-07 23:18:05 +0000315 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000316 if (!Compiler.hasDiagnostics())
317 return false;
318
319 Compiler.createSourceManager(*Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000320
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000321 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000322
Manuel Klimek3aad8552012-07-31 13:56:54 +0000323 Files->clearStatCaches();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000324 return Success;
325}
326
Manuel Klimek47c245a2012-04-04 12:07:46 +0000327ClangTool::ClangTool(const CompilationDatabase &Compilations,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000328 ArrayRef<std::string> SourcePaths,
329 std::shared_ptr<PCHContainerOperations> PCHContainerOps)
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000330 : Compilations(Compilations), SourcePaths(SourcePaths),
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000331 PCHContainerOps(std::move(PCHContainerOps)),
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000332 OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())),
333 InMemoryFileSystem(new vfs::InMemoryFileSystem),
334 Files(new FileManager(FileSystemOptions(), OverlayFileSystem)),
335 DiagConsumer(nullptr) {
336 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000337 appendArgumentsAdjuster(getClangStripOutputAdjuster());
338 appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
Sterling Augustine78f46122017-07-14 18:33:30 +0000339 appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000340}
341
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000342ClangTool::~ClangTool() {}
Manuel Klimek64083012013-11-07 23:18:05 +0000343
Manuel Klimek47c245a2012-04-04 12:07:46 +0000344void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
345 MappedFileContents.push_back(std::make_pair(FilePath, Content));
346}
347
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000348void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
349 if (ArgsAdjuster)
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000350 ArgsAdjuster =
351 combineAdjusters(std::move(ArgsAdjuster), std::move(Adjuster));
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000352 else
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000353 ArgsAdjuster = std::move(Adjuster);
Manuel Klimekd91ac932013-06-04 14:44:44 +0000354}
355
356void ClangTool::clearArgumentsAdjusters() {
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000357 ArgsAdjuster = nullptr;
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000358}
359
Benjamin Kramerb5737c12016-04-21 10:18:18 +0000360static void injectResourceDir(CommandLineArguments &Args, const char *Argv0,
361 void *MainAddr) {
362 // Allow users to override the resource dir.
363 for (StringRef Arg : Args)
364 if (Arg.startswith("-resource-dir"))
365 return;
366
367 // If there's no override in place add our resource dir.
368 Args.push_back("-resource-dir=" +
369 CompilerInvocation::GetResourcesPath(Argv0, MainAddr));
370}
371
Peter Collingbournec689ee72013-11-06 20:12:45 +0000372int ClangTool::run(ToolAction *Action) {
Alexander Kornienko8388d242012-06-04 19:02:59 +0000373 // Exists solely for the purpose of lookup of the resource path.
374 // This just needs to be some symbol in the binary.
375 static int StaticSymbol;
Alexander Kornienko8388d242012-06-04 19:02:59 +0000376
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000377 llvm::SmallString<128> InitialDirectory;
378 if (std::error_code EC = llvm::sys::fs::current_path(InitialDirectory))
379 llvm::report_fatal_error("Cannot detect current path: " +
380 Twine(EC.message()));
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000381
382 // First insert all absolute paths into the in-memory VFS. These are global
383 // for all compile commands.
384 if (SeenWorkingDirectories.insert("/").second)
385 for (const auto &MappedFile : MappedFileContents)
386 if (llvm::sys::path::is_absolute(MappedFile.first))
387 InMemoryFileSystem->addFile(
388 MappedFile.first, 0,
389 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
390
Manuel Klimek47c245a2012-04-04 12:07:46 +0000391 bool ProcessingFailed = false;
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000392 for (const auto &SourcePath : SourcePaths) {
393 std::string File(getAbsolutePath(SourcePath));
394
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000395 // Currently implementations of CompilationDatabase::getCompileCommands can
396 // change the state of the file system (e.g. prepare generated headers), so
397 // this method needs to run right before we invoke the tool, as the next
398 // file may require a different (incompatible) state of the file system.
399 //
400 // FIXME: Make the compilation database interface more explicit about the
401 // requirements to the order of invocation of its members.
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000402 std::vector<CompileCommand> CompileCommandsForFile =
403 Compilations.getCompileCommands(File);
404 if (CompileCommandsForFile.empty()) {
405 // FIXME: There are two use cases here: doing a fuzzy
406 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
407 // about the .cc files that were not found, and the use case where I
408 // specify all files I want to run over explicitly, where this should
409 // be an error. We'll want to add an option for this.
410 llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
411 continue;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000412 }
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000413 for (CompileCommand &CompileCommand : CompileCommandsForFile) {
414 // FIXME: chdir is thread hostile; on the other hand, creating the same
415 // behavior as chdir is complex: chdir resolves the path once, thus
416 // guaranteeing that all subsequent relative path operations work
417 // on the same path the original chdir resulted in. This makes a
418 // difference for example on network filesystems, where symlinks might be
419 // switched during runtime of the tool. Fixing this depends on having a
420 // file system abstraction that allows openat() style interactions.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000421 if (OverlayFileSystem->setCurrentWorkingDirectory(
422 CompileCommand.Directory))
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000423 llvm::report_fatal_error("Cannot chdir into \"" +
424 Twine(CompileCommand.Directory) + "\n!");
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000425
426 // Now fill the in-memory VFS with the relative file mappings so it will
427 // have the correct relative paths. We never remove mappings but that
428 // should be fine.
429 if (SeenWorkingDirectories.insert(CompileCommand.Directory).second)
430 for (const auto &MappedFile : MappedFileContents)
431 if (!llvm::sys::path::is_absolute(MappedFile.first))
432 InMemoryFileSystem->addFile(
433 MappedFile.first, 0,
434 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
435
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000436 std::vector<std::string> CommandLine = CompileCommand.CommandLine;
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000437 if (ArgsAdjuster)
Alexander Kornienko857b10f2015-11-05 02:19:53 +0000438 CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000439 assert(!CommandLine.empty());
Benjamin Kramerb5737c12016-04-21 10:18:18 +0000440
441 // Add the resource dir based on the binary of this tool. argv[0] in the
442 // compilation database may refer to a different compiler and we want to
443 // pick up the very same standard library that compiler is using. The
444 // builtin headers in the resource dir need to match the exact clang
445 // version the tool is using.
446 // FIXME: On linux, GetMainExecutable is independent of the value of the
447 // first argument, thus allowing ClangTool and runToolOnCode to just
448 // pass in made-up names here. Make sure this works on other platforms.
449 injectResourceDir(CommandLine, "clang_tool", &StaticSymbol);
450
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000451 // FIXME: We need a callback mechanism for the tool writer to output a
452 // customized message for each file.
453 DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000454 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
455 PCHContainerOps);
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000456 Invocation.setDiagnosticConsumer(DiagConsumer);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000457
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000458 if (!Invocation.run()) {
459 // FIXME: Diagnostics should be used instead.
460 llvm::errs() << "Error while processing " << File << ".\n";
461 ProcessingFailed = true;
462 }
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000463 // Return to the initial directory to correctly resolve next file by
464 // relative path.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000465 if (OverlayFileSystem->setCurrentWorkingDirectory(InitialDirectory.c_str()))
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000466 llvm::report_fatal_error("Cannot chdir into \"" +
467 Twine(InitialDirectory) + "\n!");
Manuel Klimek47c245a2012-04-04 12:07:46 +0000468 }
469 }
470 return ProcessingFailed ? 1 : 0;
471}
472
Peter Collingbournec689ee72013-11-06 20:12:45 +0000473namespace {
474
475class ASTBuilderAction : public ToolAction {
David Blaikie39808ff2014-04-25 14:49:37 +0000476 std::vector<std::unique_ptr<ASTUnit>> &ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000477
478public:
David Blaikie39808ff2014-04-25 14:49:37 +0000479 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000480
David Blaikieea4395e2017-01-06 19:49:01 +0000481 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
482 FileManager *Files,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000483 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000484 DiagnosticConsumer *DiagConsumer) override {
David Blaikie103a2de2014-04-25 17:01:33 +0000485 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000486 Invocation, std::move(PCHContainerOps),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000487 CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
488 DiagConsumer,
Benjamin Kramerbc632902015-10-06 14:45:20 +0000489 /*ShouldOwnClient=*/false),
490 Files);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000491 if (!AST)
492 return false;
493
David Blaikie39808ff2014-04-25 14:49:37 +0000494 ASTs.push_back(std::move(AST));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000495 return true;
496 }
497};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000498}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000499
David Blaikie39808ff2014-04-25 14:49:37 +0000500int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000501 ASTBuilderAction Action(ASTs);
502 return run(&Action);
503}
504
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000505std::unique_ptr<ASTUnit>
506buildASTFromCode(const Twine &Code, const Twine &FileName,
507 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
508 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000509 "clang-tool", std::move(PCHContainerOps));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000510}
511
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000512std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
513 const Twine &Code, const std::vector<std::string> &Args,
Benjamin Kramer987a1d22016-01-29 11:29:02 +0000514 const Twine &FileName, const Twine &ToolName,
Sterling Augustine1cda1d72017-07-06 21:02:52 +0000515 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
516 ArgumentsAdjuster Adjuster) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000517 SmallString<16> FileNameStorage;
518 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
519
David Blaikie39808ff2014-04-25 14:49:37 +0000520 std::vector<std::unique_ptr<ASTUnit>> ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000521 ASTBuilderAction Action(ASTs);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000522 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
523 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
524 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
525 new vfs::InMemoryFileSystem);
526 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Benjamin Kramerfa3dcf22015-10-06 15:04:13 +0000527 llvm::IntrusiveRefCntPtr<FileManager> Files(
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000528 new FileManager(FileSystemOptions(), OverlayFileSystem));
Sterling Augustine1cda1d72017-07-06 21:02:52 +0000529
530 ToolInvocation Invocation(
531 getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef),
532 &Action, Files.get(), std::move(PCHContainerOps));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000533
534 SmallString<1024> CodeStorage;
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000535 InMemoryFileSystem->addFile(FileNameRef, 0,
536 llvm::MemoryBuffer::getMemBuffer(
537 Code.toNullTerminatedStringRef(CodeStorage)));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000538 if (!Invocation.run())
Craig Topperccbc35e2014-05-20 04:51:16 +0000539 return nullptr;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000540
541 assert(ASTs.size() == 1);
David Blaikie103a2de2014-04-25 17:01:33 +0000542 return std::move(ASTs[0]);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000543}
544
Manuel Klimek47c245a2012-04-04 12:07:46 +0000545} // end namespace tooling
546} // end namespace clang