blob: 518fa50b4399e04ceb044adfc3bd8fd8181e727f [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"
18#include "clang/Driver/Tool.h"
19#include "clang/Frontend/CompilerInstance.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000020#include "clang/Frontend/FrontendDiagnostic.h"
21#include "clang/Frontend/TextDiagnosticPrinter.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Tooling/ArgumentsAdjusters.h"
23#include "clang/Tooling/CompilationDatabase.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000024#include "llvm/ADT/STLExtras.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000025#include "llvm/Option/Option.h"
Edwin Vane34794c52013-03-15 20:14:01 +000026#include "llvm/Support/Debug.h"
NAKAMURA Takumif0c87792012-04-04 13:59:36 +000027#include "llvm/Support/FileSystem.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000028#include "llvm/Support/Host.h"
Rafael Espindola1600a532013-06-17 17:23:47 +000029#include "llvm/Support/PathV1.h"
NAKAMURA Takumi3a64a4b2012-04-04 13:59:41 +000030#include "llvm/Support/raw_ostream.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000031
Manuel Klimek74cec542012-05-07 09:45:46 +000032// For chdir, see the comment in ClangTool::run for more information.
Manuel Klimekf33dcb02012-05-07 10:02:55 +000033#ifdef _WIN32
Manuel Klimek74cec542012-05-07 09:45:46 +000034# include <direct.h>
Manuel Klimekf33dcb02012-05-07 10:02:55 +000035#else
36# include <unistd.h>
Manuel Klimek74cec542012-05-07 09:45:46 +000037#endif
38
Manuel Klimek47c245a2012-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 Kornienko8388d242012-06-04 19:02:59 +000053 BinaryName, llvm::sys::getDefaultTargetTriple(),
Rafael Espindolab0448cd2012-11-27 16:10:37 +000054 DefaultOutputName, *Diagnostics);
Manuel Klimek47c245a2012-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 Kleckner898229a2013-06-14 17:17:23 +000062static const llvm::opt::ArgStringList *getCC1Arguments(
Manuel Klimek47c245a2012-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 Gribenkof8579502013-01-12 19:30:44 +000069 SmallString<256> error_msg;
Manuel Klimek47c245a2012-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 Kleckner898229a2013-06-14 17:17:23 +000091 const llvm::opt::ArgStringList &CC1Args) {
Manuel Klimek47c245a2012-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;
Nick Lewycky39dc9f82013-06-25 17:01:21 +000098 Invocation->getCodeGenOpts().DisableFree = false;
Manuel Klimek47c245a2012-04-04 12:07:46 +000099 return Invocation;
100}
101
102bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
103 const Twine &FileName) {
Nico Weber077a53e2012-08-30 02:02:19 +0000104 return runToolOnCodeWithArgs(
105 ToolAction, Code, std::vector<std::string>(), FileName);
106}
107
108bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
109 const std::vector<std::string> &Args,
110 const Twine &FileName) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000111 SmallString<16> FileNameStorage;
112 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
Nico Weber077a53e2012-08-30 02:02:19 +0000113 std::vector<std::string> Commands;
114 Commands.push_back("clang-tool");
115 Commands.push_back("-fsyntax-only");
116 Commands.insert(Commands.end(), Args.begin(), Args.end());
117 Commands.push_back(FileNameRef.data());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000118 FileManager Files((FileSystemOptions()));
Nico Weber077a53e2012-08-30 02:02:19 +0000119 ToolInvocation Invocation(Commands, ToolAction, &Files);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000120
121 SmallString<1024> CodeStorage;
122 Invocation.mapVirtualFile(FileNameRef,
123 Code.toNullTerminatedStringRef(CodeStorage));
124 return Invocation.run();
125}
126
Manuel Klimek65fd0e12012-07-10 13:10:51 +0000127std::string getAbsolutePath(StringRef File) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000128 SmallString<1024> BaseDirectory;
Manuel Klimek65fd0e12012-07-10 13:10:51 +0000129 if (const char *PWD = ::getenv("PWD"))
130 BaseDirectory = PWD;
131 else
132 llvm::sys::fs::current_path(BaseDirectory);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000133 SmallString<1024> PathStorage;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000134 if (llvm::sys::path::is_absolute(File)) {
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000135 llvm::sys::path::native(File, PathStorage);
136 return PathStorage.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000137 }
138 StringRef RelativePath(File);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000139 // FIXME: Should '.\\' be accepted on Win32?
Manuel Klimek47c245a2012-04-04 12:07:46 +0000140 if (RelativePath.startswith("./")) {
141 RelativePath = RelativePath.substr(strlen("./"));
142 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000143 SmallString<1024> AbsolutePath(BaseDirectory);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000144 llvm::sys::path::append(AbsolutePath, RelativePath);
NAKAMURA Takumi9b2d17c2012-05-23 22:24:20 +0000145 llvm::sys::path::native(Twine(AbsolutePath), PathStorage);
146 return PathStorage.str();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000147}
148
149ToolInvocation::ToolInvocation(
150 ArrayRef<std::string> CommandLine, FrontendAction *ToolAction,
151 FileManager *Files)
152 : CommandLine(CommandLine.vec()), ToolAction(ToolAction), Files(Files) {
153}
154
155void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
NAKAMURA Takumi4de31652012-06-02 15:34:21 +0000156 SmallString<1024> PathStorage;
157 llvm::sys::path::native(FilePath, PathStorage);
158 MappedFileContents[PathStorage] = Content;
Manuel Klimek47c245a2012-04-04 12:07:46 +0000159}
160
161bool ToolInvocation::run() {
162 std::vector<const char*> Argv;
163 for (int I = 0, E = CommandLine.size(); I != E; ++I)
164 Argv.push_back(CommandLine[I].c_str());
165 const char *const BinaryName = Argv[0];
Douglas Gregor811db4e2012-10-23 22:26:28 +0000166 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000167 TextDiagnosticPrinter DiagnosticPrinter(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000168 llvm::errs(), &*DiagOpts);
169 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000170 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()),
Douglas Gregor811db4e2012-10-23 22:26:28 +0000171 &*DiagOpts, &DiagnosticPrinter, false);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000172
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000173 const OwningPtr<clang::driver::Driver> Driver(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000174 newDriver(&Diagnostics, BinaryName));
175 // Since the input might only be virtual, don't check whether it exists.
176 Driver->setCheckInputsExist(false);
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000177 const OwningPtr<clang::driver::Compilation> Compilation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000178 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
Reid Kleckner898229a2013-06-14 17:17:23 +0000179 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000180 &Diagnostics, Compilation.get());
181 if (CC1Args == NULL) {
182 return false;
183 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000184 OwningPtr<clang::CompilerInvocation> Invocation(
Manuel Klimek47c245a2012-04-04 12:07:46 +0000185 newInvocation(&Diagnostics, *CC1Args));
Sean Silvaf1b49e22013-01-20 01:58:28 +0000186 return runInvocation(BinaryName, Compilation.get(), Invocation.take());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000187}
188
Manuel Klimek47c245a2012-04-04 12:07:46 +0000189bool ToolInvocation::runInvocation(
190 const char *BinaryName,
191 clang::driver::Compilation *Compilation,
Sean Silvaf1b49e22013-01-20 01:58:28 +0000192 clang::CompilerInvocation *Invocation) {
Manuel Klimek47c245a2012-04-04 12:07:46 +0000193 // Show the invocation, with -v.
194 if (Invocation->getHeaderSearchOpts().Verbose) {
195 llvm::errs() << "clang Invocation:\n";
196 Compilation->PrintJob(llvm::errs(), Compilation->getJobs(), "\n", true);
197 llvm::errs() << "\n";
198 }
199
200 // Create a compiler instance to handle the actual work.
201 clang::CompilerInstance Compiler;
202 Compiler.setInvocation(Invocation);
203 Compiler.setFileManager(Files);
204 // FIXME: What about LangOpts?
205
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000206 // ToolAction can have lifetime requirements for Compiler or its members, and
207 // we need to ensure it's deleted earlier than Compiler. So we pass it to an
208 // OwningPtr declared after the Compiler variable.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000209 OwningPtr<FrontendAction> ScopedToolAction(ToolAction.take());
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000210
Manuel Klimek47c245a2012-04-04 12:07:46 +0000211 // Create the compilers actual diagnostics engine.
Sean Silvaf1b49e22013-01-20 01:58:28 +0000212 Compiler.createDiagnostics();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000213 if (!Compiler.hasDiagnostics())
214 return false;
215
216 Compiler.createSourceManager(*Files);
217 addFileMappingsTo(Compiler.getSourceManager());
218
Alexander Kornienko21d6ec92012-05-31 17:58:43 +0000219 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000220
221 Compiler.resetAndLeakFileManager();
Manuel Klimek3aad8552012-07-31 13:56:54 +0000222 Files->clearStatCaches();
Manuel Klimek47c245a2012-04-04 12:07:46 +0000223 return Success;
224}
225
226void ToolInvocation::addFileMappingsTo(SourceManager &Sources) {
227 for (llvm::StringMap<StringRef>::const_iterator
228 It = MappedFileContents.begin(), End = MappedFileContents.end();
229 It != End; ++It) {
230 // Inject the code as the given file name into the preprocessor options.
231 const llvm::MemoryBuffer *Input =
232 llvm::MemoryBuffer::getMemBuffer(It->getValue());
233 // FIXME: figure out what '0' stands for.
234 const FileEntry *FromFile = Files->getVirtualFile(
235 It->getKey(), Input->getBufferSize(), 0);
Alexander Kornienko9e8d2282012-05-30 12:10:28 +0000236 Sources.overrideFileContents(FromFile, Input);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000237 }
238}
239
240ClangTool::ClangTool(const CompilationDatabase &Compilations,
241 ArrayRef<std::string> SourcePaths)
Pavel Labathdee20c12013-06-06 11:52:19 +0000242 : Files((FileSystemOptions())) {
243 ArgsAdjusters.push_back(new ClangStripOutputAdjuster());
244 ArgsAdjusters.push_back(new ClangSyntaxOnlyAdjuster());
Manuel Klimek47c245a2012-04-04 12:07:46 +0000245 for (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000246 SmallString<1024> File(getAbsolutePath(SourcePaths[I]));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000247
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000248 std::vector<CompileCommand> CompileCommandsForFile =
Manuel Klimek47c245a2012-04-04 12:07:46 +0000249 Compilations.getCompileCommands(File.str());
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000250 if (!CompileCommandsForFile.empty()) {
251 for (int I = 0, E = CompileCommandsForFile.size(); I != E; ++I) {
252 CompileCommands.push_back(std::make_pair(File.str(),
253 CompileCommandsForFile[I]));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000254 }
255 } else {
256 // FIXME: There are two use cases here: doing a fuzzy
257 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care
258 // about the .cc files that were not found, and the use case where I
259 // specify all files I want to run over explicitly, where this should
260 // be an error. We'll want to add an option for this.
261 llvm::outs() << "Skipping " << File << ". Command line not found.\n";
262 }
263 }
264}
265
266void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
267 MappedFileContents.push_back(std::make_pair(FilePath, Content));
268}
269
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000270void ClangTool::setArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
Manuel Klimekd91ac932013-06-04 14:44:44 +0000271 clearArgumentsAdjusters();
272 appendArgumentsAdjuster(Adjuster);
273}
274
275void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
276 ArgsAdjusters.push_back(Adjuster);
277}
278
279void ClangTool::clearArgumentsAdjusters() {
280 for (unsigned I = 0, E = ArgsAdjusters.size(); I != E; ++I)
281 delete ArgsAdjusters[I];
282 ArgsAdjusters.clear();
Simon Atanasyan32df72d2012-05-09 16:18:30 +0000283}
284
Manuel Klimek47c245a2012-04-04 12:07:46 +0000285int ClangTool::run(FrontendActionFactory *ActionFactory) {
Alexander Kornienko8388d242012-06-04 19:02:59 +0000286 // Exists solely for the purpose of lookup of the resource path.
287 // This just needs to be some symbol in the binary.
288 static int StaticSymbol;
289 // The driver detects the builtin header path based on the path of the
290 // executable.
291 // FIXME: On linux, GetMainExecutable is independent of the value of the
292 // first argument, thus allowing ClangTool and runToolOnCode to just
293 // pass in made-up names here. Make sure this works on other platforms.
294 std::string MainExecutable =
Rafael Espindola9678d272013-06-26 05:03:40 +0000295 llvm::sys::fs::getMainExecutable("clang_tool", &StaticSymbol);
Alexander Kornienko8388d242012-06-04 19:02:59 +0000296
Manuel Klimek47c245a2012-04-04 12:07:46 +0000297 bool ProcessingFailed = false;
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000298 for (unsigned I = 0; I < CompileCommands.size(); ++I) {
299 std::string File = CompileCommands[I].first;
300 // FIXME: chdir is thread hostile; on the other hand, creating the same
301 // behavior as chdir is complex: chdir resolves the path once, thus
302 // guaranteeing that all subsequent relative path operations work
303 // on the same path the original chdir resulted in. This makes a difference
Alexander Kornienko8388d242012-06-04 19:02:59 +0000304 // for example on network filesystems, where symlinks might be switched
Manuel Klimek805d8dc2012-05-07 09:17:48 +0000305 // during runtime of the tool. Fixing this depends on having a file system
306 // abstraction that allows openat() style interactions.
307 if (chdir(CompileCommands[I].second.Directory.c_str()))
308 llvm::report_fatal_error("Cannot chdir into \"" +
309 CompileCommands[I].second.Directory + "\n!");
Manuel Klimekd91ac932013-06-04 14:44:44 +0000310 std::vector<std::string> CommandLine = CompileCommands[I].second.CommandLine;
311 for (unsigned I = 0, E = ArgsAdjusters.size(); I != E; ++I)
312 CommandLine = ArgsAdjusters[I]->Adjust(CommandLine);
Alexander Kornienko8388d242012-06-04 19:02:59 +0000313 assert(!CommandLine.empty());
314 CommandLine[0] = MainExecutable;
Edwin Vane34794c52013-03-15 20:14:01 +0000315 // FIXME: We need a callback mechanism for the tool writer to output a
316 // customized message for each file.
317 DEBUG({
318 llvm::dbgs() << "Processing: " << File << ".\n";
319 });
Manuel Klimek47c245a2012-04-04 12:07:46 +0000320 ToolInvocation Invocation(CommandLine, ActionFactory->create(), &Files);
321 for (int I = 0, E = MappedFileContents.size(); I != E; ++I) {
322 Invocation.mapVirtualFile(MappedFileContents[I].first,
323 MappedFileContents[I].second);
324 }
325 if (!Invocation.run()) {
Edwin Vane34794c52013-03-15 20:14:01 +0000326 // FIXME: Diagnostics should be used instead.
327 llvm::errs() << "Error while processing " << File << ".\n";
Manuel Klimek47c245a2012-04-04 12:07:46 +0000328 ProcessingFailed = true;
329 }
330 }
331 return ProcessingFailed ? 1 : 0;
332}
333
334} // end namespace tooling
335} // end namespace clang