blob: 4f3edf323f0958db18ea01df357544ef0c489076 [file] [log] [blame]
Manuel Klimekcb971c62012-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 Klimekcb971c62012-04-04 12:07:46 +000016#include "clang/Driver/Compilation.h"
17#include "clang/Driver/Driver.h"
18#include "clang/Driver/Tool.h"
19#include "clang/Frontend/CompilerInstance.h"
Manuel Klimekcb971c62012-04-04 12:07:46 +000020#include "clang/Frontend/FrontendDiagnostic.h"
21#include "clang/Frontend/TextDiagnosticPrinter.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Tooling/ArgumentsAdjusters.h"
23#include "clang/Tooling/CompilationDatabase.h"
NAKAMURA Takumi01b8ca52012-04-04 13:59:41 +000024#include "llvm/ADT/STLExtras.h"
Reid Klecknerb1e25a12013-06-14 17:17:23 +000025#include "llvm/Option/Option.h"
Edwin Vanead7e1602013-03-15 20:14:01 +000026#include "llvm/Support/Debug.h"
NAKAMURA Takumib175d0f2012-04-04 13:59:36 +000027#include "llvm/Support/FileSystem.h"
NAKAMURA Takumi01b8ca52012-04-04 13:59:41 +000028#include "llvm/Support/Host.h"
Rafael Espindolaa372f402013-06-17 17:23:47 +000029#include "llvm/Support/PathV1.h"
NAKAMURA Takumi01b8ca52012-04-04 13:59:41 +000030#include "llvm/Support/raw_ostream.h"
Manuel Klimekcb971c62012-04-04 12:07:46 +000031
Manuel Klimek3b6e3192012-05-07 09:45:46 +000032// For chdir, see the comment in ClangTool::run for more information.
Manuel Klimeked5ee482012-05-07 10:02:55 +000033#ifdef _WIN32
Manuel Klimek3b6e3192012-05-07 09:45:46 +000034# include <direct.h>
Manuel Klimeked5ee482012-05-07 10:02:55 +000035#else
36# include <unistd.h>
Manuel Klimek3b6e3192012-05-07 09:45:46 +000037#endif
38
Manuel Klimekcb971c62012-04-04 12:07:46 +000039namespace clang {
40namespace tooling {
41
42FrontendActionFactory::~FrontendActionFactory() {}
43
44// FIXME: This file contains structural duplication with other parts of the
45// code that sets up a compiler to run tools on it, and we should refactor
46// it to be based on the same framework.
47
48/// \brief Builds a clang driver initialized for running clang tools.
49static clang::driver::Driver *newDriver(clang::DiagnosticsEngine *Diagnostics,
50 const char *BinaryName) {
51 const std::string DefaultOutputName = "a.out";
52 clang::driver::Driver *CompilerDriver = new clang::driver::Driver(
Alexander Kornienko30c009b2012-06-04 19:02:59 +000053 BinaryName, llvm::sys::getDefaultTargetTriple(),
Rafael Espindola17c874a2012-11-27 16:10:37 +000054 DefaultOutputName, *Diagnostics);
Manuel Klimekcb971c62012-04-04 12:07:46 +000055 CompilerDriver->setTitle("clang_based_tool");
56 return CompilerDriver;
57}
58
59/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs.
60///
61/// Returns NULL on error.
Reid Klecknerb1e25a12013-06-14 17:17:23 +000062static const llvm::opt::ArgStringList *getCC1Arguments(
Manuel Klimekcb971c62012-04-04 12:07:46 +000063 clang::DiagnosticsEngine *Diagnostics,
64 clang::driver::Compilation *Compilation) {
65 // We expect to get back exactly one Command job, if we didn't something
66 // failed. Extract that job from the Compilation.
67 const clang::driver::JobList &Jobs = Compilation->getJobs();
68 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000069 SmallString<256> error_msg;
Manuel Klimekcb971c62012-04-04 12:07:46 +000070 llvm::raw_svector_ostream error_stream(error_msg);
71 Compilation->PrintJob(error_stream, Compilation->getJobs(), "; ", true);
72 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job)
73 << error_stream.str();
74 return NULL;
75 }
76
77 // The one job we find should be to invoke clang again.
78 const clang::driver::Command *Cmd =
79 cast<clang::driver::Command>(*Jobs.begin());
80 if (StringRef(Cmd->getCreator().getName()) != "clang") {
81 Diagnostics->Report(clang::diag::err_fe_expected_clang_command);
82 return NULL;
83 }
84
85 return &Cmd->getArguments();
86}
87
88/// \brief Returns a clang build invocation initialized from the CC1 flags.
89static clang::CompilerInvocation *newInvocation(
90 clang::DiagnosticsEngine *Diagnostics,
Reid Klecknerb1e25a12013-06-14 17:17:23 +000091 const llvm::opt::ArgStringList &CC1Args) {
Manuel Klimekcb971c62012-04-04 12:07:46 +000092 assert(!CC1Args.empty() && "Must at least contain the program name!");
93 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation;
94 clang::CompilerInvocation::CreateFromArgs(
95 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
96 *Diagnostics);
97 Invocation->getFrontendOpts().DisableFree = false;
98 return Invocation;
99}
100
101bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
102 const Twine &FileName) {
Nico Weber56669882012-08-30 02:02:19 +0000103 return runToolOnCodeWithArgs(
104 ToolAction, Code, std::vector<std::string>(), FileName);
105}
106
107bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
108 const std::vector<std::string> &Args,
109 const Twine &FileName) {
Manuel Klimekcb971c62012-04-04 12:07:46 +0000110 SmallString<16> FileNameStorage;
111 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
Nico Weber56669882012-08-30 02:02:19 +0000112 std::vector<std::string> Commands;
113 Commands.push_back("clang-tool");
114 Commands.push_back("-fsyntax-only");
115 Commands.insert(Commands.end(), Args.begin(), Args.end());
116 Commands.push_back(FileNameRef.data());
Manuel Klimekcb971c62012-04-04 12:07:46 +0000117 FileManager Files((FileSystemOptions()));
Nico Weber56669882012-08-30 02:02:19 +0000118 ToolInvocation Invocation(Commands, ToolAction, &Files);
Manuel Klimekcb971c62012-04-04 12:07:46 +0000119
120 SmallString<1024> CodeStorage;
121 Invocation.mapVirtualFile(FileNameRef,
122 Code.toNullTerminatedStringRef(CodeStorage));
123 return Invocation.run();
124}
125
Manuel Klimek8fa2fb82012-07-10 13:10:51 +0000126std::string getAbsolutePath(StringRef File) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000127 SmallString<1024> BaseDirectory;
Manuel Klimek8fa2fb82012-07-10 13:10:51 +0000128 if (const char *PWD = ::getenv("PWD"))
129 BaseDirectory = PWD;
130 else
131 llvm::sys::fs::current_path(BaseDirectory);
NAKAMURA Takumi62d198c2012-05-23 22:24:20 +0000132 SmallString<1024> PathStorage;
Manuel Klimekcb971c62012-04-04 12:07:46 +0000133 if (llvm::sys::path::is_absolute(File)) {
NAKAMURA Takumi62d198c2012-05-23 22:24:20 +0000134 llvm::sys::path::native(File, PathStorage);
135 return PathStorage.str();
Manuel Klimekcb971c62012-04-04 12:07:46 +0000136 }
137 StringRef RelativePath(File);
NAKAMURA Takumi62d198c2012-05-23 22:24:20 +0000138 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimekcb971c62012-04-04 12:07:46 +0000139 if (RelativePath.startswith("./")) {
140 RelativePath = RelativePath.substr(strlen("./"));
141 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000142 SmallString<1024> AbsolutePath(BaseDirectory);
Manuel Klimekcb971c62012-04-04 12:07:46 +0000143 llvm::sys::path::append(AbsolutePath, RelativePath);
NAKAMURA Takumi62d198c2012-05-23 22:24:20 +0000144 llvm::sys::path::native(Twine(AbsolutePath), PathStorage);
145 return PathStorage.str();
Manuel Klimekcb971c62012-04-04 12:07:46 +0000146}
147
148ToolInvocation::ToolInvocation(
149 ArrayRef<std::string> CommandLine, FrontendAction *ToolAction,
150 FileManager *Files)
151 : CommandLine(CommandLine.vec()), ToolAction(ToolAction), Files(Files) {
152}
153
154void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi0ef8db22012-06-02 15:34:21 +0000155 SmallString<1024> PathStorage;
156 llvm::sys::path::native(FilePath, PathStorage);
157 MappedFileContents[PathStorage] = Content;
Manuel Klimekcb971c62012-04-04 12:07:46 +0000158}
159
160bool ToolInvocation::run() {
161 std::vector<const char*> Argv;
162 for (int I = 0, E = CommandLine.size(); I != E; ++I)
163 Argv.push_back(CommandLine[I].c_str());
164 const char *const BinaryName = Argv[0];
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000165 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Manuel Klimekcb971c62012-04-04 12:07:46 +0000166 TextDiagnosticPrinter DiagnosticPrinter(
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000167 llvm::errs(), &*DiagOpts);
168 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000169 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()),
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000170 &*DiagOpts, &DiagnosticPrinter, false);
Manuel Klimekcb971c62012-04-04 12:07:46 +0000171
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000172 const OwningPtr<clang::driver::Driver> Driver(
Manuel Klimekcb971c62012-04-04 12:07:46 +0000173 newDriver(&Diagnostics, BinaryName));
174 // Since the input might only be virtual, don't check whether it exists.
175 Driver->setCheckInputsExist(false);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000176 const OwningPtr<clang::driver::Compilation> Compilation(
Manuel Klimekcb971c62012-04-04 12:07:46 +0000177 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
Reid Klecknerb1e25a12013-06-14 17:17:23 +0000178 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
Manuel Klimekcb971c62012-04-04 12:07:46 +0000179 &Diagnostics, Compilation.get());
180 if (CC1Args == NULL) {
181 return false;
182 }
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000183 OwningPtr<clang::CompilerInvocation> Invocation(
Manuel Klimekcb971c62012-04-04 12:07:46 +0000184 newInvocation(&Diagnostics, *CC1Args));
Sean Silvad47afb92013-01-20 01:58:28 +0000185 return runInvocation(BinaryName, Compilation.get(), Invocation.take());
Manuel Klimekcb971c62012-04-04 12:07:46 +0000186}
187
Manuel Klimekcb971c62012-04-04 12:07:46 +0000188bool ToolInvocation::runInvocation(
189 const char *BinaryName,
190 clang::driver::Compilation *Compilation,
Sean Silvad47afb92013-01-20 01:58:28 +0000191 clang::CompilerInvocation *Invocation) {
Manuel Klimekcb971c62012-04-04 12:07:46 +0000192 // Show the invocation, with -v.
193 if (Invocation->getHeaderSearchOpts().Verbose) {
194 llvm::errs() << "clang Invocation:\n";
195 Compilation->PrintJob(llvm::errs(), Compilation->getJobs(), "\n", true);
196 llvm::errs() << "\n";
197 }
198
199 // Create a compiler instance to handle the actual work.
200 clang::CompilerInstance Compiler;
201 Compiler.setInvocation(Invocation);
202 Compiler.setFileManager(Files);
203 // FIXME: What about LangOpts?
204
Alexander Kornienko14a19242012-05-31 17:58:43 +0000205 // ToolAction can have lifetime requirements for Compiler or its members, and
206 // we need to ensure it's deleted earlier than Compiler. So we pass it to an
207 // OwningPtr declared after the Compiler variable.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000208 OwningPtr<FrontendAction> ScopedToolAction(ToolAction.take());
Alexander Kornienko14a19242012-05-31 17:58:43 +0000209
Manuel Klimekcb971c62012-04-04 12:07:46 +0000210 // Create the compilers actual diagnostics engine.
Sean Silvad47afb92013-01-20 01:58:28 +0000211 Compiler.createDiagnostics();
Manuel Klimekcb971c62012-04-04 12:07:46 +0000212 if (!Compiler.hasDiagnostics())
213 return false;
214
215 Compiler.createSourceManager(*Files);
216 addFileMappingsTo(Compiler.getSourceManager());
217
Alexander Kornienko14a19242012-05-31 17:58:43 +0000218 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimekcb971c62012-04-04 12:07:46 +0000219
220 Compiler.resetAndLeakFileManager();
Manuel Klimek98be8602012-07-31 13:56:54 +0000221 Files->clearStatCaches();
Manuel Klimekcb971c62012-04-04 12:07:46 +0000222 return Success;
223}
224
225void ToolInvocation::addFileMappingsTo(SourceManager &Sources) {
226 for (llvm::StringMap<StringRef>::const_iterator
227 It = MappedFileContents.begin(), End = MappedFileContents.end();
228 It != End; ++It) {
229 // Inject the code as the given file name into the preprocessor options.
230 const llvm::MemoryBuffer *Input =
231 llvm::MemoryBuffer::getMemBuffer(It->getValue());
232 // FIXME: figure out what '0' stands for.
233 const FileEntry *FromFile = Files->getVirtualFile(
234 It->getKey(), Input->getBufferSize(), 0);
Alexander Kornienko240193b2012-05-30 12:10:28 +0000235 Sources.overrideFileContents(FromFile, Input);
Manuel Klimekcb971c62012-04-04 12:07:46 +0000236 }
237}
238
239ClangTool::ClangTool(const CompilationDatabase &Compilations,
240 ArrayRef<std::string> SourcePaths)
Pavel Labath63d53352013-06-06 11:52:19 +0000241 : Files((FileSystemOptions())) {
242 ArgsAdjusters.push_back(new ClangStripOutputAdjuster());
243 ArgsAdjusters.push_back(new ClangSyntaxOnlyAdjuster());
Manuel Klimekcb971c62012-04-04 12:07:46 +0000244 for (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000245 SmallString<1024> File(getAbsolutePath(SourcePaths[I]));
Manuel Klimekcb971c62012-04-04 12:07:46 +0000246
Manuel Klimek00f3c4f2012-05-07 09:17:48 +0000247 std::vector<CompileCommand> CompileCommandsForFile =
Manuel Klimekcb971c62012-04-04 12:07:46 +0000248 Compilations.getCompileCommands(File.str());
Manuel Klimek00f3c4f2012-05-07 09:17:48 +0000249 if (!CompileCommandsForFile.empty()) {
250 for (int I = 0, E = CompileCommandsForFile.size(); I != E; ++I) {
251 CompileCommands.push_back(std::make_pair(File.str(),
252 CompileCommandsForFile[I]));
Manuel Klimekcb971c62012-04-04 12:07:46 +0000253 }
254 } else {
255 // FIXME: There are two use cases here: doing a fuzzy
256 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
257 // about the .cc files that were not found, and the use case where I
258 // specify all files I want to run over explicitly, where this should
259 // be an error. We'll want to add an option for this.
260 llvm::outs() << "Skipping " << File << ". Command line not found.\n";
261 }
262 }
263}
264
265void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
266 MappedFileContents.push_back(std::make_pair(FilePath, Content));
267}
268
Simon Atanasyana01ddc72012-05-09 16:18:30 +0000269void ClangTool::setArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
Manuel Klimek48b3f0f2013-06-04 14:44:44 +0000270 clearArgumentsAdjusters();
271 appendArgumentsAdjuster(Adjuster);
272}
273
274void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
275 ArgsAdjusters.push_back(Adjuster);
276}
277
278void ClangTool::clearArgumentsAdjusters() {
279 for (unsigned I = 0, E = ArgsAdjusters.size(); I != E; ++I)
280 delete ArgsAdjusters[I];
281 ArgsAdjusters.clear();
Simon Atanasyana01ddc72012-05-09 16:18:30 +0000282}
283
Manuel Klimekcb971c62012-04-04 12:07:46 +0000284int ClangTool::run(FrontendActionFactory *ActionFactory) {
Alexander Kornienko30c009b2012-06-04 19:02:59 +0000285 // Exists solely for the purpose of lookup of the resource path.
286 // This just needs to be some symbol in the binary.
287 static int StaticSymbol;
288 // The driver detects the builtin header path based on the path of the
289 // executable.
290 // FIXME: On linux, GetMainExecutable is independent of the value of the
291 // first argument, thus allowing ClangTool and runToolOnCode to just
292 // pass in made-up names here. Make sure this works on other platforms.
293 std::string MainExecutable =
294 llvm::sys::Path::GetMainExecutable("clang_tool", &StaticSymbol).str();
295
Manuel Klimekcb971c62012-04-04 12:07:46 +0000296 bool ProcessingFailed = false;
Manuel Klimek00f3c4f2012-05-07 09:17:48 +0000297 for (unsigned I = 0; I < CompileCommands.size(); ++I) {
298 std::string File = CompileCommands[I].first;
299 // FIXME: chdir is thread hostile; on the other hand, creating the same
300 // behavior as chdir is complex: chdir resolves the path once, thus
301 // guaranteeing that all subsequent relative path operations work
302 // on the same path the original chdir resulted in. This makes a difference
Alexander Kornienko30c009b2012-06-04 19:02:59 +0000303 // for example on network filesystems, where symlinks might be switched
Manuel Klimek00f3c4f2012-05-07 09:17:48 +0000304 // during runtime of the tool. Fixing this depends on having a file system
305 // abstraction that allows openat() style interactions.
306 if (chdir(CompileCommands[I].second.Directory.c_str()))
307 llvm::report_fatal_error("Cannot chdir into \"" +
308 CompileCommands[I].second.Directory + "\n!");
Manuel Klimek48b3f0f2013-06-04 14:44:44 +0000309 std::vector<std::string> CommandLine = CompileCommands[I].second.CommandLine;
310 for (unsigned I = 0, E = ArgsAdjusters.size(); I != E; ++I)
311 CommandLine = ArgsAdjusters[I]->Adjust(CommandLine);
Alexander Kornienko30c009b2012-06-04 19:02:59 +0000312 assert(!CommandLine.empty());
313 CommandLine[0] = MainExecutable;
Edwin Vanead7e1602013-03-15 20:14:01 +0000314 // FIXME: We need a callback mechanism for the tool writer to output a
315 // customized message for each file.
316 DEBUG({
317 llvm::dbgs() << "Processing: " << File << ".\n";
318 });
Manuel Klimekcb971c62012-04-04 12:07:46 +0000319 ToolInvocation Invocation(CommandLine, ActionFactory->create(), &Files);
320 for (int I = 0, E = MappedFileContents.size(); I != E; ++I) {
321 Invocation.mapVirtualFile(MappedFileContents[I].first,
322 MappedFileContents[I].second);
323 }
324 if (!Invocation.run()) {
Edwin Vanead7e1602013-03-15 20:14:01 +0000325 // FIXME: Diagnostics should be used instead.
326 llvm::errs() << "Error while processing " << File << ".\n";
Manuel Klimekcb971c62012-04-04 12:07:46 +0000327 ProcessingFailed = true;
328 }
329 }
330 return ProcessingFailed ? 1 : 0;
331}
332
333} // end namespace tooling
334} // end namespace clang