blob: 220b62558bfbcbc9036e5adb01f745a4d95ecc72 [file] [log] [blame]
Manuel Klimek47c245a2012-04-04 12:07:46 +00001//===--- Tooling.cpp - Running clang standalone tools ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements functions to run clang tools standalone instead
11// of running them as a plugin.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Tooling/Tooling.h"
Peter Collingbournec689ee72013-11-06 20:12:45 +000016#include "clang/AST/ASTConsumer.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000017#include "clang/Driver/Compilation.h"
18#include "clang/Driver/Driver.h"
19#include "clang/Driver/Tool.h"
Manuel Klimek9b30e2b2015-10-06 10:45:03 +000020#include "clang/Driver/ToolChain.h"
Peter Collingbournec689ee72013-11-06 20:12:45 +000021#include "clang/Frontend/ASTUnit.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000022#include "clang/Frontend/CompilerInstance.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000023#include "clang/Frontend/FrontendDiagnostic.h"
24#include "clang/Frontend/TextDiagnosticPrinter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Tooling/ArgumentsAdjusters.h"
26#include "clang/Tooling/CompilationDatabase.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000027#include "llvm/ADT/STLExtras.h"
Alp Toker1d257e12014-06-04 03:28:55 +000028#include "llvm/Config/llvm-config.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000029#include "llvm/Option/Option.h"
Edwin Vane34794c52013-03-15 20:14:01 +000030#include "llvm/Support/Debug.h"
NAKAMURA Takumif0c87792012-04-04 13:59:36 +000031#include "llvm/Support/FileSystem.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000032#include "llvm/Support/Host.h"
33#include "llvm/Support/raw_ostream.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000034
Chandler Carruth57f5fbe2014-04-21 22:55:36 +000035#define DEBUG_TYPE "clang-tooling"
36
Manuel Klimek47c245a2012-04-04 12:07:46 +000037namespace clang {
38namespace tooling {
39
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000040ToolAction::~ToolAction() {}
Peter Collingbournec689ee72013-11-06 20:12:45 +000041
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000042FrontendActionFactory::~FrontendActionFactory() {}
Manuel Klimek47c245a2012-04-04 12:07:46 +000043
44// FIXME: This file contains structural duplication with other parts of the
45// code that sets up a compiler to run tools on it, and we should refactor
46// it to be based on the same framework.
47
48/// \brief Builds a clang driver initialized for running clang tools.
Benjamin Kramer407eb792015-10-09 13:03:25 +000049static clang::driver::Driver *newDriver(
50 clang::DiagnosticsEngine *Diagnostics, const char *BinaryName,
51 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000052 clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
Benjamin Kramer407eb792015-10-09 13:03:25 +000053 BinaryName, llvm::sys::getDefaultTargetTriple(), *Diagnostics, VFS);
Manuel Klimek47c245a2012-04-04 12:07:46 +000054 CompilerDriver->setTitle("clang_based_tool");
55 return CompilerDriver;
56}
57
58/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
59///
60/// Returns NULL on error.
Reid Kleckner898229a2013-06-14 17:17:23 +000061static const llvm::opt::ArgStringList *getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +000062 clang::DiagnosticsEngine *Diagnostics,
63 clang::driver::Compilation *Compilation) {
64 // We expect to get back exactly one Command job, if we didn't something
65 // failed. Extract that job from the Compilation.
66 const clang::driver::JobList &Jobs = Compilation->getJobs();
Justin Bogneraab97922014-10-03 01:04:53 +000067 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000068 SmallString<256> error_msg;
Manuel Klimek47c245a2012-04-04 12:07:46 +000069 llvm::raw_svector_ostream error_stream(error_msg);
Hans Wennborgb212b342013-09-12 18:23:34 +000070 Jobs.Print(error_stream, "; ", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +000071 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
72 << error_stream.str();
Craig Topperccbc35e2014-05-20 04:51:16 +000073 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +000074 }
75
76 // The one job we find should be to invoke clang again.
David Blaikiec11bf802014-09-04 16:04:28 +000077 const clang::driver::Command &Cmd =
Justin Bogneraab97922014-10-03 01:04:53 +000078 cast<clang::driver::Command>(*Jobs.begin());
David Blaikiec11bf802014-09-04 16:04:28 +000079 if (StringRef(Cmd.getCreator().getName()) != "clang") {
Manuel Klimek47c245a2012-04-04 12:07:46 +000080 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
Craig Topperccbc35e2014-05-20 04:51:16 +000081 return nullptr;
Manuel Klimek47c245a2012-04-04 12:07:46 +000082 }
83
David Blaikiec11bf802014-09-04 16:04:28 +000084 return &Cmd.getArguments();
Manuel Klimek47c245a2012-04-04 12:07:46 +000085}
86
87/// \brief Returns a clang build invocation initialized from the CC1 flags.
Manuel Klimekbea7dfb2015-03-28 00:42:36 +000088clang::CompilerInvocation *newInvocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +000089 clang::DiagnosticsEngine *Diagnostics,
Reid Kleckner898229a2013-06-14 17:17:23 +000090 const llvm::opt::ArgStringList &CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000091 assert(!CC1Args.empty() && "Must at least contain the program name!");
92 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
93 clang::CompilerInvocation::CreateFromArgs(
94 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
95 *Diagnostics);
96 Invocation->getFrontendOpts().DisableFree = false;
Nick Lewycky39dc9f82013-06-25 17:01:21 +000097 Invocation->getCodeGenOpts().DisableFree = false;
Peter Collingbournec0423b32014-03-02 23:37:26 +000098 Invocation->getDependencyOutputOpts() = DependencyOutputOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +000099 return Invocation;
100}
101
102bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000103 const Twine &FileName,
104 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
105 return runToolOnCodeWithArgs(ToolAction, Code, std::vector<std::string>(),
106 FileName, PCHContainerOps);
Nico Weber077a53e2012-08-30 02:02:19 +0000107}
108
Peter Collingbournec689ee72013-11-06 20:12:45 +0000109static std::vector<std::string>
110getSyntaxOnlyToolArgs(const std::vector<std::string> &ExtraArgs,
111 StringRef FileName) {
112 std::vector<std::string> Args;
113 Args.push_back("clang-tool");
114 Args.push_back("-fsyntax-only");
115 Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
116 Args.push_back(FileName.str());
117 return Args;
118}
119
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000120bool runToolOnCodeWithArgs(
121 clang::FrontendAction *ToolAction, const Twine &Code,
122 const std::vector<std::string> &Args, const Twine &FileName,
123 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
124 const FileContentMappings &VirtualMappedFiles) {
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000125
Manuel Klimek47c245a2012-04-04 12:07:46 +0000126 SmallString<16> FileNameStorage;
127 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000128 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
129 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
130 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
131 new vfs::InMemoryFileSystem);
132 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000133 llvm::IntrusiveRefCntPtr<FileManager> Files(
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000134 new FileManager(FileSystemOptions(), OverlayFileSystem));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000135 ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000136 ToolAction, Files.get(), PCHContainerOps);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000137
138 SmallString<1024> CodeStorage;
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000139 InMemoryFileSystem->addFile(FileNameRef, 0,
140 llvm::MemoryBuffer::getMemBuffer(
141 Code.toNullTerminatedStringRef(CodeStorage)));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000142
143 for (auto &FilenameWithContent : VirtualMappedFiles) {
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000144 InMemoryFileSystem->addFile(
145 FilenameWithContent.first, 0,
146 llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
Manuel Klimekd3aa1f42014-11-25 17:01:06 +0000147 }
148
Manuel Klimek47c245a2012-04-04 12:07:46 +0000149 return Invocation.run();
150}
151
Manuel Klimek65fd0e12012-07-10 13:10:51 +0000152std::string getAbsolutePath(StringRef File) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000153 StringRef RelativePath(File);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000154 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimek47c245a2012-04-04 12:07:46 +0000155 if (RelativePath.startswith("./")) {
156 RelativePath = RelativePath.substr(strlen("./"));
157 }
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000158
159 SmallString<1024> AbsolutePath = RelativePath;
Rafael Espindolac0809172014-06-12 14:02:15 +0000160 std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath);
Rafael Espindolac7367ff2013-08-10 01:40:10 +0000161 assert(!EC);
Rafael Espindola0b8e4a12013-08-10 04:25:53 +0000162 (void)EC;
Benjamin Kramer2d4d8cb2013-09-11 11:23:15 +0000163 llvm::sys::path::native(AbsolutePath);
164 return AbsolutePath.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000165}
166
Manuel Klimek9b30e2b2015-10-06 10:45:03 +0000167void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
168 StringRef InvokedAs) {
169 if (!CommandLine.empty() && !InvokedAs.empty()) {
170 bool AlreadyHasTarget = false;
171 bool AlreadyHasMode = false;
172 // Skip CommandLine[0].
173 for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();
174 ++Token) {
175 StringRef TokenRef(*Token);
176 AlreadyHasTarget |=
177 (TokenRef == "-target" || TokenRef.startswith("-target="));
178 AlreadyHasMode |= (TokenRef == "--driver-mode" ||
179 TokenRef.startswith("--driver-mode="));
180 }
181 auto TargetMode =
182 clang::driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs);
183 if (!AlreadyHasMode && !TargetMode.second.empty()) {
184 CommandLine.insert(++CommandLine.begin(), TargetMode.second);
185 }
186 if (!AlreadyHasTarget && !TargetMode.first.empty()) {
187 CommandLine.insert(++CommandLine.begin(), {"-target", TargetMode.first});
188 }
189 }
190}
191
Peter Collingbournec689ee72013-11-06 20:12:45 +0000192namespace {
193
194class SingleFrontendActionFactory : public FrontendActionFactory {
195 FrontendAction *Action;
196
197public:
198 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
199
Craig Topperfb6b25b2014-03-15 04:29:04 +0000200 FrontendAction *create() override { return Action; }
Peter Collingbournec689ee72013-11-06 20:12:45 +0000201};
202
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000203}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000204
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000205ToolInvocation::ToolInvocation(
206 std::vector<std::string> CommandLine, ToolAction *Action,
207 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
208 : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false),
209 Files(Files), PCHContainerOps(PCHContainerOps), DiagConsumer(nullptr) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000210
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000211ToolInvocation::ToolInvocation(
212 std::vector<std::string> CommandLine, FrontendAction *FAction,
213 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000214 : CommandLine(std::move(CommandLine)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000215 Action(new SingleFrontendActionFactory(FAction)), OwnsAction(true),
216 Files(Files), PCHContainerOps(PCHContainerOps), DiagConsumer(nullptr) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000217
218ToolInvocation::~ToolInvocation() {
219 if (OwnsAction)
220 delete Action;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000221}
222
223void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi4de31652012-06-02 15:34:21 +0000224 SmallString<1024> PathStorage;
225 llvm::sys::path::native(FilePath, PathStorage);
226 MappedFileContents[PathStorage] = Content;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000227}
228
229bool ToolInvocation::run() {
230 std::vector<const char*> Argv;
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000231 for (const std::string &Str : CommandLine)
232 Argv.push_back(Str.c_str());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000233 const char *const BinaryName = Argv[0];
Douglas Gregor811db4e2012-10-23 22:26:28 +0000234 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000235 TextDiagnosticPrinter DiagnosticPrinter(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000236 llvm::errs(), &*DiagOpts);
237 DiagnosticsEngine Diagnostics(
Manuel Klimek64083012013-11-07 23:18:05 +0000238 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
239 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000240
Ahmed Charlesb8984322014-03-07 20:03:18 +0000241 const std::unique_ptr<clang::driver::Driver> Driver(
Benjamin Kramer407eb792015-10-09 13:03:25 +0000242 newDriver(&Diagnostics, BinaryName, Files->getVirtualFileSystem()));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000243 // Since the input might only be virtual, don't check whether it exists.
244 Driver->setCheckInputsExist(false);
Ahmed Charlesb8984322014-03-07 20:03:18 +0000245 const std::unique_ptr<clang::driver::Compilation> Compilation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000246 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
Reid Kleckner898229a2013-06-14 17:17:23 +0000247 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000248 &Diagnostics, Compilation.get());
Craig Topperccbc35e2014-05-20 04:51:16 +0000249 if (!CC1Args) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000250 return false;
251 }
Ahmed Charlesb8984322014-03-07 20:03:18 +0000252 std::unique_ptr<clang::CompilerInvocation> Invocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000253 newInvocation(&Diagnostics, *CC1Args));
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000254 // FIXME: remove this when all users have migrated!
Benjamin Kramerefb1eb92014-03-20 12:48:36 +0000255 for (const auto &It : MappedFileContents) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000256 // Inject the code as the given file name into the preprocessor options.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000257 std::unique_ptr<llvm::MemoryBuffer> Input =
258 llvm::MemoryBuffer::getMemBuffer(It.getValue());
259 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
260 Input.release());
Peter Collingbournec689ee72013-11-06 20:12:45 +0000261 }
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000262 return runInvocation(BinaryName, Compilation.get(), Invocation.release(),
263 PCHContainerOps);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000264}
265
Manuel Klimek47c245a2012-04-04 12:07:46 +0000266bool ToolInvocation::runInvocation(
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000267 const char *BinaryName, clang::driver::Compilation *Compilation,
268 clang::CompilerInvocation *Invocation,
269 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000270 // Show the invocation, with -v.
271 if (Invocation->getHeaderSearchOpts().Verbose) {
272 llvm::errs() << "clang Invocation:\n";
Hans Wennborgb212b342013-09-12 18:23:34 +0000273 Compilation->getJobs().Print(llvm::errs(), "\n", true);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000274 llvm::errs() << "\n";
275 }
276
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000277 return Action->runInvocation(Invocation, Files, PCHContainerOps,
278 DiagConsumer);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000279}
280
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000281bool FrontendActionFactory::runInvocation(
282 CompilerInvocation *Invocation, FileManager *Files,
283 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
284 DiagnosticConsumer *DiagConsumer) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000285 // Create a compiler instance to handle the actual work.
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000286 clang::CompilerInstance Compiler(PCHContainerOps);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000287 Compiler.setInvocation(Invocation);
288 Compiler.setFileManager(Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000289
Peter Collingbournec689ee72013-11-06 20:12:45 +0000290 // The FrontendAction can have lifetime requirements for Compiler or its
291 // members, and we need to ensure it's deleted earlier than Compiler. So we
Ahmed Charlesb8984322014-03-07 20:03:18 +0000292 // pass it to an std::unique_ptr declared after the Compiler variable.
293 std::unique_ptr<FrontendAction> ScopedToolAction(create());
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000294
Alp Toker77273fc2014-05-16 13:45:29 +0000295 // Create the compiler's actual diagnostics engine.
Manuel Klimek64083012013-11-07 23:18:05 +0000296 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000297 if (!Compiler.hasDiagnostics())
298 return false;
299
300 Compiler.createSourceManager(*Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000301
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000302 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000303
Manuel Klimek3aad8552012-07-31 13:56:54 +0000304 Files->clearStatCaches();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000305 return Success;
306}
307
Manuel Klimek47c245a2012-04-04 12:07:46 +0000308ClangTool::ClangTool(const CompilationDatabase &Compilations,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000309 ArrayRef<std::string> SourcePaths,
310 std::shared_ptr<PCHContainerOperations> PCHContainerOps)
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000311 : Compilations(Compilations), SourcePaths(SourcePaths),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000312 PCHContainerOps(PCHContainerOps),
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000313 OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())),
314 InMemoryFileSystem(new vfs::InMemoryFileSystem),
315 Files(new FileManager(FileSystemOptions(), OverlayFileSystem)),
316 DiagConsumer(nullptr) {
317 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000318 appendArgumentsAdjuster(getClangStripOutputAdjuster());
319 appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000320}
321
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000322ClangTool::~ClangTool() {}
Manuel Klimek64083012013-11-07 23:18:05 +0000323
Manuel Klimek47c245a2012-04-04 12:07:46 +0000324void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
325 MappedFileContents.push_back(std::make_pair(FilePath, Content));
326}
327
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000328void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
329 if (ArgsAdjuster)
330 ArgsAdjuster = combineAdjusters(ArgsAdjuster, Adjuster);
331 else
332 ArgsAdjuster = Adjuster;
Manuel Klimekd91ac932013-06-04 14:44:44 +0000333}
334
335void ClangTool::clearArgumentsAdjusters() {
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000336 ArgsAdjuster = nullptr;
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000337}
338
Peter Collingbournec689ee72013-11-06 20:12:45 +0000339int ClangTool::run(ToolAction *Action) {
Alexander Kornienko8388d242012-06-04 19:02:59 +0000340 // Exists solely for the purpose of lookup of the resource path.
341 // This just needs to be some symbol in the binary.
342 static int StaticSymbol;
343 // The driver detects the builtin header path based on the path of the
344 // executable.
345 // FIXME: On linux, GetMainExecutable is independent of the value of the
346 // first argument, thus allowing ClangTool and runToolOnCode to just
347 // pass in made-up names here. Make sure this works on other platforms.
348 std::string MainExecutable =
Rafael Espindola9678d272013-06-26 05:03:40 +0000349 llvm::sys::fs::getMainExecutable("clang_tool", &StaticSymbol);
Alexander Kornienko8388d242012-06-04 19:02:59 +0000350
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000351 llvm::SmallString<128> InitialDirectory;
352 if (std::error_code EC = llvm::sys::fs::current_path(InitialDirectory))
353 llvm::report_fatal_error("Cannot detect current path: " +
354 Twine(EC.message()));
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000355
356 // First insert all absolute paths into the in-memory VFS. These are global
357 // for all compile commands.
358 if (SeenWorkingDirectories.insert("/").second)
359 for (const auto &MappedFile : MappedFileContents)
360 if (llvm::sys::path::is_absolute(MappedFile.first))
361 InMemoryFileSystem->addFile(
362 MappedFile.first, 0,
363 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
364
Manuel Klimek47c245a2012-04-04 12:07:46 +0000365 bool ProcessingFailed = false;
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000366 for (const auto &SourcePath : SourcePaths) {
367 std::string File(getAbsolutePath(SourcePath));
368
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000369 // Currently implementations of CompilationDatabase::getCompileCommands can
370 // change the state of the file system (e.g. prepare generated headers), so
371 // this method needs to run right before we invoke the tool, as the next
372 // file may require a different (incompatible) state of the file system.
373 //
374 // FIXME: Make the compilation database interface more explicit about the
375 // requirements to the order of invocation of its members.
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000376 std::vector<CompileCommand> CompileCommandsForFile =
377 Compilations.getCompileCommands(File);
378 if (CompileCommandsForFile.empty()) {
379 // FIXME: There are two use cases here: doing a fuzzy
380 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
381 // about the .cc files that were not found, and the use case where I
382 // specify all files I want to run over explicitly, where this should
383 // be an error. We'll want to add an option for this.
384 llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
385 continue;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000386 }
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000387 for (CompileCommand &CompileCommand : CompileCommandsForFile) {
388 // FIXME: chdir is thread hostile; on the other hand, creating the same
389 // behavior as chdir is complex: chdir resolves the path once, thus
390 // guaranteeing that all subsequent relative path operations work
391 // on the same path the original chdir resulted in. This makes a
392 // difference for example on network filesystems, where symlinks might be
393 // switched during runtime of the tool. Fixing this depends on having a
394 // file system abstraction that allows openat() style interactions.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000395 if (OverlayFileSystem->setCurrentWorkingDirectory(
396 CompileCommand.Directory))
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000397 llvm::report_fatal_error("Cannot chdir into \"" +
398 Twine(CompileCommand.Directory) + "\n!");
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000399
400 // Now fill the in-memory VFS with the relative file mappings so it will
401 // have the correct relative paths. We never remove mappings but that
402 // should be fine.
403 if (SeenWorkingDirectories.insert(CompileCommand.Directory).second)
404 for (const auto &MappedFile : MappedFileContents)
405 if (!llvm::sys::path::is_absolute(MappedFile.first))
406 InMemoryFileSystem->addFile(
407 MappedFile.first, 0,
408 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
409
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000410 std::vector<std::string> CommandLine = CompileCommand.CommandLine;
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000411 if (ArgsAdjuster)
412 CommandLine = ArgsAdjuster(CommandLine);
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000413 assert(!CommandLine.empty());
414 CommandLine[0] = MainExecutable;
415 // FIXME: We need a callback mechanism for the tool writer to output a
416 // customized message for each file.
417 DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000418 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
419 PCHContainerOps);
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000420 Invocation.setDiagnosticConsumer(DiagConsumer);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000421
Alexander Kornienko9a45fac2014-08-27 21:36:39 +0000422 if (!Invocation.run()) {
423 // FIXME: Diagnostics should be used instead.
424 llvm::errs() << "Error while processing " << File << ".\n";
425 ProcessingFailed = true;
426 }
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000427 // Return to the initial directory to correctly resolve next file by
428 // relative path.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000429 if (OverlayFileSystem->setCurrentWorkingDirectory(InitialDirectory.c_str()))
Alexander Kornienkoc48a5352014-11-10 15:42:31 +0000430 llvm::report_fatal_error("Cannot chdir into \"" +
431 Twine(InitialDirectory) + "\n!");
Manuel Klimek47c245a2012-04-04 12:07:46 +0000432 }
433 }
434 return ProcessingFailed ? 1 : 0;
435}
436
Peter Collingbournec689ee72013-11-06 20:12:45 +0000437namespace {
438
439class ASTBuilderAction : public ToolAction {
David Blaikie39808ff2014-04-25 14:49:37 +0000440 std::vector<std::unique_ptr<ASTUnit>> &ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000441
442public:
David Blaikie39808ff2014-04-25 14:49:37 +0000443 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000444
Manuel Klimek64083012013-11-07 23:18:05 +0000445 bool runInvocation(CompilerInvocation *Invocation, FileManager *Files,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000446 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000447 DiagnosticConsumer *DiagConsumer) override {
David Blaikie103a2de2014-04-25 17:01:33 +0000448 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000449 Invocation, PCHContainerOps,
450 CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
451 DiagConsumer,
Benjamin Kramerbc632902015-10-06 14:45:20 +0000452 /*ShouldOwnClient=*/false),
453 Files);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000454 if (!AST)
455 return false;
456
David Blaikie39808ff2014-04-25 14:49:37 +0000457 ASTs.push_back(std::move(AST));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000458 return true;
459 }
460};
461
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000462}
Peter Collingbournec689ee72013-11-06 20:12:45 +0000463
David Blaikie39808ff2014-04-25 14:49:37 +0000464int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000465 ASTBuilderAction Action(ASTs);
466 return run(&Action);
467}
468
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000469std::unique_ptr<ASTUnit>
470buildASTFromCode(const Twine &Code, const Twine &FileName,
471 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
472 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
473 PCHContainerOps);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000474}
475
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000476std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
477 const Twine &Code, const std::vector<std::string> &Args,
478 const Twine &FileName,
479 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
Peter Collingbournec689ee72013-11-06 20:12:45 +0000480 SmallString<16> FileNameStorage;
481 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
482
David Blaikie39808ff2014-04-25 14:49:37 +0000483 std::vector<std::unique_ptr<ASTUnit>> ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000484 ASTBuilderAction Action(ASTs);
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000485 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
486 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
487 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
488 new vfs::InMemoryFileSystem);
489 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
Benjamin Kramerfa3dcf22015-10-06 15:04:13 +0000490 llvm::IntrusiveRefCntPtr<FileManager> Files(
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000491 new FileManager(FileSystemOptions(), OverlayFileSystem));
Craig Topperccbc35e2014-05-20 04:51:16 +0000492 ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), &Action,
Benjamin Kramerfa3dcf22015-10-06 15:04:13 +0000493 Files.get(), PCHContainerOps);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000494
495 SmallString<1024> CodeStorage;
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000496 InMemoryFileSystem->addFile(FileNameRef, 0,
497 llvm::MemoryBuffer::getMemBuffer(
498 Code.toNullTerminatedStringRef(CodeStorage)));
Peter Collingbournec689ee72013-11-06 20:12:45 +0000499 if (!Invocation.run())
Craig Topperccbc35e2014-05-20 04:51:16 +0000500 return nullptr;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000501
502 assert(ASTs.size() == 1);
David Blaikie103a2de2014-04-25 17:01:33 +0000503 return std::move(ASTs[0]);
Peter Collingbournec689ee72013-11-06 20:12:45 +0000504}
505
Manuel Klimek47c245a2012-04-04 12:07:46 +0000506} // end namespace tooling
507} // end namespace clang